#!/bin/sh
#
# Gtkdialog to execute program as root from a WM menu.
# (c) SliTaz GNU/Linux 2008-2010 - GNU gpl.
#
VERSION=20100324

# Usage.
if [ -z "$1" ]; then
    echo "SliTaz subox version : $VERSION"
    echo -e "\nUsage : subox program\n"
    exit 0
fi

# Nothing to do if we are root
test $(id -u) = 0 && exec $1

# Include gettext helper script.
. /usr/bin/gettext.sh

# Export package name for gettext.
TEXTDOMAIN='subox'
export TEXTDOMAIN

# Keep command in an exported variable to be used by SU_DIALOG.
export SU_CMD=$1

# Error window if the pwd is wrong.
export ERROR_DIALOG='
<window title="Subox">
  <vbox>

    <text use-markup="true">
      <label>"
<b>SliTaz - Subox</b>"
      </label>
    </text>
    <text wrap="true" width-chars="48">
	<label>"'`gettext "Error: wrong password!"`'"</label>
    </text>

    <hbox>
      <button ok></button>
    </hbox>
</vbox>
</window>
'

# Main window and root password default entry set to 'root'.
SU_DIALOG='
<window title="Subox" skip_taskbar_hint="true">
<vbox>

	<text use-markup="true">
		<label>"
<b>SliTaz - Subox</b>"
		</label>
	</text>
	<text wrap="true" width-chars="50">
		<label>"'`gettext "
Please enter root password (default root) to execute :"`'
'$@'
"
		</label>
	</text>
	
	<hbox>
		<text use-markup="true">
			<label>"'`gettext "<b>Admin password :</b>"`'"</label>
		</text>
		<entry visibility="false">'

# Check if we have a saved passwd.
if [ -s $HOME/.config/slitaz/subox.conf ]; then
	PASSWD=`cat $HOME/.config/slitaz/subox.conf`
	[ -n "$PASSWD" ] && SU_DIALOG="$SU_DIALOG <default>$PASSWD</default>" && AUTO_SAVED_PASSWD=true
else 
AUTO_SAVED_PASSWD=false
fi

export SU_DIALOG=''${SU_DIALOG}'
			<variable>PASSWD</variable>
		</entry>
	</hbox>
	
	<hbox>
		<checkbox>
			
			<label>"'`gettext "Autosave password"`'"</label>
			<variable>AUTOSAVE</variable>'
if [ $AUTO_SAVED_PASSWD = "true" ]
	then SU_DIALOG="$SU_DIALOG <default>true</default>"
	else SU_DIALOG="$SU_DIALOG <default>false</default>"
fi

export SU_DIALOG=''${SU_DIALOG}'
			
		</checkbox>
		<button ok>
			<action> echo $PASSWD | su -c "$SU_CMD &" || gtkdialog --center --program=ERROR_DIALOG</action>
			<action>[ $AUTOSAVE = true ] && echo $PASSWD > '$HOME/.config/slitaz/subox.conf'</action>
			<action>[ $AUTOSAVE = true ] && chmod 0600 '$HOME/.config/slitaz/subox.conf'</action>
			<action>[ $AUTOSAVE = false ] && cat /dev/null > '$HOME/.config/slitaz/subox.conf'</action>
			<action type="closewindow">SU_DIALOG</action>
		</button>
		<button cancel></button>
	</hbox>

</vbox>
</window>'

gtkdialog --center --program=SU_DIALOG > /dev/null

exit 0
