#! /bin/bash

# Pearl SU allowing users to give a password
# and run graphical commands as root
#
# 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="$*"

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

#CLEARCMD=`echo "$CMD" | sed -e 's|./||'`

mainmenu () {
# get password
PASS=$(yad --class="GSu" \
    --width=400 \
    --center \
    --title="$LOCAL1" \
    --text="\n$LOCAL2:\n<b>root</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 \
	--image="dialog-password" \
	--window-icon="dialog-password" \
	--text="\n$LOCAL4"
	mainmenu
fi
}

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

runmenu () {
# grant access to xserver for root user
xhost +root@ &> /dev/null

# run command
#SPIN="$(mktemp -u --tmpdir spsu.in.XXXXXXXXX)"
#SPOUT="$(mktemp -u --tmpdir spsu.out.XXXXXXXXX)"

export PATH=$PATH:/usr/local/bin:/bin:/usr/bin:/sbin:/usr/sbin
#LC_MESSAGES=C empty -f -i $SPIN -o $SPOUT su -p root -c "$CMD"
#[[ $? -eq 0 ]] && empty -w -i $SPOUT -o $SPIN "word:" "$PASS\n"
echo "$PASS" | su -p root -c "$CMD"
}

mainmenu
passmenu
passcheckmenu
runmenu
