#!/bin/sh
#
# gnsu: gnsu's not su

PASSWORDTRIES=3
CMD_DISPLAY="$*"
LIBEXECDIR=/usr/libexec

# Exit codes for when the command is not run at all, following pkexec's
# convention. Anything else gnsu returns is the exit code of the command.
DISMISSED=126
NOTAUTHORIZED=127

init() {
	# Translations only work with utf8 locales
	if ! locale -k charmap|grep -q UTF-8 ; then
		LANG=C
	fi

	export u=`whoami`

	export TRUE=/usr/bin/true
	export SUDO=/usr/bin/sudo

	export SUDO_ASKPASS=$LIBEXECDIR/gnsu-helper
	export GNSU_ASKPASS=$LIBEXECDIR/gnsu-askpass

	export COUNT=$PASSWORDTRIES
}

help() {
	cat <<- EOF
	Usage: gnsu [SUDO OPTIONS] command [COMMAND ARGUMENTS]
	Run a command as another user through sudo
	
	OPTIONS:
	        -h, --help           Show this help
	EOF
}

storedpass() {
	$SUDO -n $TRUE 2> /dev/null
	return $?
}

askpass() {
	if [ $COUNT -lt $PASSWORDTRIES ]; then
		PERMISSION="-p"
	else
		PERMISSION=""
	fi
	GNSU_PASSWORD=$( $GNSU_ASKPASS \
		--title="$CMD_DISPLAY" \
		--user="$u" \
		$PERMISSION \
		2> /dev/null)
	retval=$?
	if [ $retval -eq $DISMISSED ]; then
		exit $DISMISSED
	elif [ $retval -ne 0 ]; then
		exit $NOTAUTHORIZED
	fi
	export GNSU_PASSWORD
}

trypass() {
	$SUDO -A $TRUE 2> /dev/null
	return $?
}

execcommand() {
	$SUDO -A "$@"
}

execcommandnopass() {
	$SUDO "$@"
}

passwordloop() {
	if [ $COUNT -gt 0 ]; then
		askpass
		trypass
		retval=$?
		if [ $retval -eq 0 ]; then
			execcommand "$@"
			exit
		else
			COUNT=$(($COUNT - 1))
			passwordloop "$@"
		fi
	else
		exit $NOTAUTHORIZED
	fi
}

case $1 in
	-h | --help | "" )
	help
	exit
	;;
esac

init
storedpass
retval=$?
if [ $retval -eq 0 ]; then
	execcommandnopass "$@"
else
	passwordloop "$@"
fi

