#! /bin/bash

# Pearl SUDO allowing users to give a password
# and run graphical commands as a super user
#
# Created by Paweł "pavroo" Pijanowski 2018/12/16
# Inspired by Graphical frontend for su(1) script
# from https://sourceforge.net/p/yad-dialog/wiki/Examples/
# Copyright 2018-2021 under the GNU GPL3 License
# Last updated 2021/04/01

# get default's locale file
DEFLOCDIR="/usr/share/pearl/pearl-su"
if [ "`cat /etc/default/locale | grep LANG= | grep de`" != "" ]; then
. $DEFLOCDIR/de
elif [ "`cat /etc/default/locale | grep LANG= | grep el`" != "" ]; then
. $DEFLOCDIR/el
elif [ "`cat /etc/default/locale | grep LANG= | grep es`" != "" ]; then
. $DEFLOCDIR/es
elif [ "`cat /etc/default/locale | grep LANG= | grep fr`" != "" ]; then
. $DEFLOCDIR/fr
elif [ "`cat /etc/default/locale | grep LANG= | grep hu`" != "" ]; then
. $DEFLOCDIR/hu
elif [ "`cat /etc/default/locale | grep LANG= | grep it`" != "" ]; then
. $DEFLOCDIR/it
elif [ "`cat /etc/default/locale | grep LANG= | grep pl`" != "" ]; then
. $DEFLOCDIR/pl
elif [ "`cat /etc/default/locale | grep LANG= | grep pt_BR`" != "" ]; then
. $DEFLOCDIR/pt_BR
elif [ "`cat /etc/default/locale | grep LANG= | grep ru`" != "" ]; then
. $DEFLOCDIR/ru
elif [ "`cat /etc/default/locale | grep LANG= | grep zh_CN`" != "" ]; then
. $DEFLOCDIR/zh_CN
else
. $DEFLOCDIR/en
fi

CMD="$*"
ME=`whoami`

if [ "$CMD" = "" ]; then
	echo ""
	echo "spsudo usage is as follows:"
	echo "spsudo <command>"
	echo ""
	exit 1
fi

if [ "$ME" = "root" ]; then
	echo "do not run spsudo as root... exiting..."
	exit 1
fi

mainmenu () {
# get password
PASS=$(yad --class="GSu" \
	--title="$LOCAL1" \
	--width=400 --center \
	--text="\n$LOCAL2:\n<b>$ME</b>\n\n$LOCAL3:\n<b>$CMD</b> \n" \
	--image="dialog-password" \
	--window-icon="dialog-password" \
	--entry --hide-text)
}

passmenu () {
if [ "$PASS" = "" ]; then
	echo "$LOCAL4"
	yad --button=Ok:0 \
	--title="$LOCAL1" \
	--width=400 --center \
	--text="\n$LOCAL4" \
	--image="dialog-password" \
	--window-icon="dialog-password"
	mainmenu
fi
}

passcheckmenu () {
if [ "$PASS" != "" ]; then
	sudo pearl-pass-check $ME $PASS
	if [ -f /tmp/pearl-passcheck ]; then
		CHECKPASS=`cat /tmp/pearl-passcheck | grep true`
		if [ "$CHECKPASS" = "" ]; then
		#echo "$LOCAL5 $ME !"
			yad --button=Ok:0 \
			--title="$LOCAL1" \
			--width=400 --center \
			--image="dialog-password" \
			--window-icon="dialog-password" \
			--text="\n$LOCAL5:\n<b>$ME</b> \n\n$LOCAL6"
			mainmenu
		fi
	fi
fi
}

runmenu () {
# run an app with sudo
echo "$PASS" | sudo -S $CMD
# remove privilege
sudo -K
exit 0
}

mainmenu
passmenu
passcheckmenu
runmenu
