#!/bin/dash
# dash and ash but not bash!
# generic wrapper to run as spot (when currently running as root)
# (C) James Budiono 2012, 2017
# 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 }
'
}

SPOT_HOME=$(awk -F: '$1=="spot" {print $6}' /etc/passwd)
CURDIR=$PWD
if [ $(id -u) -eq 0 ]; then
	[ -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
	mkdir -p $XDG_DATA_HOME; chown spot:spot $XDG_DATA_HOME
	export FATDOG_STATE_DIR=$SPOT_HOME/.fatdog

	set -- "$(eval_safe_quote "$@")"

	exec su spot -s /bin/dash -c '
# try to switch to original directory, unless it is /root
! [ "'"$CURDIR"'" = /root ] && cd "'"$CURDIR"'"
'"$@"'
'
else
	exec "$@"
fi
