#!/bin/dash
# Enable/disable root-enabled companion .desktop items for run-as-spot apps
# jamesbond 2019

APPTITLE="Fatdog64 Run-As-Root"
APPS_DIR=/usr/share/applications

# $1-dir (do not end with slash)
get_spot_apps() {
	grep -l "^Exec=.*-spot" "$1"/*desktop | sed "s|$1/||; /.*-root.desktop$/d; s|.desktop$||"
}

# $1-dir $*
have_root_companion() {
	local p dir
	dir="$1"
	shift
	for p; do
		[ -e "$dir"/${p}-root.desktop ] && echo $p
	done
}

# $1-spot apps, $2-root apps
build_list() {
	{ echo "$1"; echo '==='; echo "$2"; } | awk '
BEGIN { doroot=0 }
/===/ { doroot=1 }
!/===/ {
	if (!doroot) spot[$1]=$1
	else root[$1]=$1
}
END {
	for (p in spot) {
		if (root[p]) print p " " p " on "
		else print p " " p " off "
	}
}
'
}

# $1-dir $* apps
clean_existing_root_apps() {
	local p dir
	dir="$1"
	shift
	for p; do
		[ -e "$dir"/${p}-root.desktop ] && rm "$dir"/${p}-root.desktop
	done
}

create_root_app() {
	local p dir
	dir="$1"
	shift
	for p; do
		cp "$dir"/$p.desktop "$dir"/${p}-root.desktop
		case $p in
			*google-chrome*)
				sed -i -e '/^Name,*=/ s/$/ ROOT/' \
					-e '/^Exec=/ s/-spot/-stable --no-sandbox/' "$dir"/${p}-root.desktop ;;
			*)
				sed -i -e '/^Name,*=/ s/$/ ROOT/' \
					-e '/^Exec=/ s/-spot//' "$dir"/${p}-root.desktop ;;
		esac
	done
}

### main ###
[ $(id -u) -ne 0 ] && exec gtksu "Fatdog Run-As-Root" "$0"
SPOT_APPS="$(get_spot_apps $APPS_DIR)"
ROOT_APPS="$(have_root_companion $APPS_DIR $SPOT_APPS)"
LIST="$(build_list "$SPOT_APPS" "$ROOT_APPS")"

# ask
if CHOSEN=$(Xdialog --title "$APPTITLE" --stdout --separate-output --buildlist " \
Items on the left are applications that usually run as spot.
Items on the right are applications that will run as ROOT.
Move items between left and right as needed.
" 0 0 0 $LIST); then
	clean_existing_root_apps $APPS_DIR $SPOT_APPS
	create_root_app $APPS_DIR $CHOSEN
else
	Xdialog --title "$APPTITLE" --infobox "Cancelled. Nothing is changed." 0 0 10000
fi
