#!/bin/bash
# persistence script for wdisplays via kanshi-gen
# 260120 radky

function wdisplays_options() {
	XPIX=$(wlr-randr | grep current | grep -oP '\d+x\d+' | cut -d 'x' -f1)
	YPIX=$(wlr-randr | grep current | cut -d'x' -f2 | cut -d' ' -f1)
	PROFILE=$(ls -t ~/.config/kanshi/*.profile | tr ' ' 'n\\' | head -n1)
	SCALE=$(grep -oP 'scale \K\d+\.\d+' $PROFILE | grep -v 'disable' | tail -n1)
	yad --title="Wdisplays" \
	--borders=15 \
	--text-align=center \
	--text="\n<b>Screen: ${XPIX}x${YPIX} @ ${SCALE} dpi</b>\n\nChanging the screen resolution,\nDPI scale or font size will change\nthe xy coordinates of desk icons.\n\nAfter changing screen settings\nplease set the icon layout again\nto recalibrate the new desktop.\n\nSee Help for usage guidelines.\n" \
	--button="Help":1 \
	--button="Cancel":0 \
	--button="OK":2
	ret=$?
	if [ "$ret" == 1 ]; then
		mdview ~/.config/spacefm/docs/help.md
		if [ -f /tmp/wdisplays-flag ]; then
			rm -f /tmp/wdisplays-flag
			desktop-icon-manager &
		fi
		exit
	elif [ "$ret" == 2 ]; then
		TS1=$(stat -c %Y "$PROFILE")
		wdisplays
		kanshi-gen
		sleep 0.5
		particons
		TS2=$(stat -c %Y "$PROFILE")
		[ "$TS2" = "$TS1" ] && exit
		yad --title="Reminder" \
		--borders=20 \
		--text-align=center \
		--text="\nSet the icon layout again to recalibrate the desktop.\n" \
		--buttons-layout=center \
		--button="OK:0"
		desktop-icon-layout
		exit
	else
		if [ -f /tmp/wdisplays-flag ]; then
			rm -f /tmp/wdisplays-flag
			desktop-icon-manager &
		fi
		exit
	fi
}

if	[ -e ~/.config/autostart/zzzfm.desktop ]; then
	wdisplays_options
else
	wdisplays
	kanshi-gen
fi
