#!/bin/dash
# generic wrapper to run as spot (when currently running as root)
# (C) James Budiono 2012, 2017, 2019
# License: GPL version 3 or later
# 20170920 step: add eval_safe_quote for safe execution.
# 20200628 step:
# - 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) -eq 0 ]; then
	SPOT_HOME=$(awk -F: '$1=="spot" {print $6}' /etc/passwd)

	[ -z "$XAUTHORITY" ] && XAUTHORITY=/root/.Xauthority
	[ -e "$XAUTHORITY" ] && cp $XAUTHORITY $SPOT_HOME/.Xauthority &&
	chown spot:spot $SPOT_HOME/.Xauthority &&
	export XAUTHORITY=$SPOT_HOME/.Xauthority

	export XDG_CONFIG_HOME=$SPOT_HOME/.config
	export XDG_CACHE_HOME=$SPOT_HOME/.cache
	export XDG_DATA_HOME=$SPOT_HOME/.local/share
	export XDG_RUNTIME_DIR=/tmp/runtime-spot
	mkdir -p $XDG_DATA_HOME $XDG_RUNTIME_DIR
	chown spot:spot $XDG_DATA_HOME $XDG_RUNTIME_DIR
	chmod 0700 $XDG_RUNTIME_DIR # for my eyes only
	export FATDOG_STATE_DIR=$SPOT_HOME/.fatdog

	if [ $# = 0 ]; then
		exec su spot -s /bin/sh
	else
		# switch to SPOT_HOME if /root
		[ "$PWD" = /root ] && cd "$SPOT_HOME"

		set_SQA "$@"
		exec su spot -s /bin/dash -c "$SQA"
	fi
else
	exec "$@"
fi
