#!/bin/dash
# generic wrapper to run as root.
# 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.
# 20200628 step:
# - split out from sudo
# - replace eval_safe_quote with set_SQA
# - fix invalid usage: su -s dash -c "$@"
# - unit test script: tests/run-as-sudo.sh

[ ${SUDO_TEST:-0} -gt 1 ] && set -x

# Single quote each argument.
set_SQA() {
	local p SQ
	for p; do
		_sq "$p"
		SQA="$SQA $_SQ"
	done
	SQA=${SQA# }
}

# Rewrite all single quotes as \'
# Adapted from https://unix.stackexchange.com/a/187787
_sq() {
	set \' "$1"
	while	case $2 in
			*\'*) : ;;
			*) ! _SQ="$1$2'" ;;
		esac
	do
		set "$1${2%%\'*}'\''" "${2#*\'}"
	done
}

if [ $(id -u) -ne 0 ]; then
	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 [ $# -ne 0 ]; then
			exec gtksu "Privilege Escalation" "$@"
		fi
	else
		## launched from terminal
		[ "$XAUTHORITY" ] & export XAUTHORITY=$ROOT_HOME/.Xauthority

		if [ $# = 0 ]; then
			exec su -s /bin/sh
		else
			set_SQA "$@"
			exec su -s /bin/dash -c "$SQA"
		fi

	fi
else
	exec "$@"
fi
