#!/bin/dash
# dash and ash but not bash!
# Poor man's sudo. No facility to avoid asking for password. It will __always__ ask for password.
# (C) James Budiono 2020
# License: GPL version 3 or later
# 20170920 step: add eval_safe_quote for safe execution.
#
eval_safe_quote() # $@
# Use this shell's 'set' command to consistently quote values with exterior
# Single Quotes (SQ). The SQ character itself is quoted differently according
# to each shell. This implementation is for dash and ash, which quote SQ as
# "'" and ''"'", respectively.
{
	local a stop="$(od -An -N4 -i /dev/urandom)"
	for a; do a="${a}
$stop"; set; done | awk -v Q="'" '# awk, gawk, mawk
f!=1 &&  /^a=/        { printf "%s", substr($0,3); f=1; next }
f==1 && !/^'"$stop"'/ { printf "\n%s", $0; next }
f==1 &&  /^'"$stop"'/ { printf Q" "; f=0; next }
'
}

### as sudo, parameter cannot be blank
if [ ${0##*/} = "sudo" ]; then
	if [ $# -eq 0 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
		echo "Usage: sudo command [args]" && exit
	fi
fi

###
if [ $(id -u) -ne 0 ]; then
	NUMPARAMS=$#
	ROOT_HOME=$(awk -F: '$1=="root" {print $6}' /etc/passwd)

	export XDG_CONFIG_HOME=$ROOT_HOME/.config
	export XDG_CACHE_HOME=$ROOT_HOME/.cache
	export XDG_DATA_HOME=$ROOT_HOME/.local/share
	export XDG_RUNTIME_DIR=/tmp/runtime-root
	mkdir -p $XDG_DATA_HOME $XDG_RUNTIME_DIR 2> /dev/null
	export FATDOG_STATE_DIR=$ROOT_HOME/.fatdog
	
	if ! test -t 0 && test -n "$DISPLAY"; then
		## launched from GUI
		if [ $NUMPARAMS -ne 0 ]; then
			exec gtksu "Privilege Escalation" "$@"
		fi
	else
		## launched from terminal
		[ "$XAUTHORITY" ] & export XAUTHORITY=$ROOT_HOME/.Xauthority

		if [ $NUMPARAMS = 0 ]; then
			exec su -s /bin/sh
		else
			set -- "$(eval_safe_quote "$@")"		
			exec su -s /bin/dash -c "$@"
		fi

	fi
else
	exec "$@"
fi
