#!/bin/sh
#
# SliTaz tiny GUI boxes for the desktop (su, logout, locale, etc)
# and as usual, please: KISS
#
# Note: $(gettext "text") doesn't work inside Yad so use `gettext \"text\"`
#
# Copyright (C) 2011 SliTaz GNU/linux - GNU gpl v3
#    - Christophe Lincoln <pankso@slitaz.org>
#

# Download dir (may be in a config file)
DOWNLOADS=$HOME/Downloads

# Internationalization
. /usr/bin/gettext.sh
TEXTDOMAIN='tazbox'
export TEXTDOMAIN

# Icons for most windows
icon=/usr/share/pixmaps/slitaz-menu.png

# some constants to be used inside functions
tmp="/tmp/keymap.list"
db="/usr/share/i18n/locales"
zi="/usr/share/zoneinfo/"

#
# Functions
#

usage() {
	cat << EOT

$(gettext "Usage:") $(basename $0) [command]

$(gettext "Commands:")
  usage      $(gettext "Display this short help usage")
  su         $(gettext "Execute a command as super-user")
  logout     $(gettext "Desktop logout box with actions")
  out        $(gettext "Pipe a command output into a GTK window")
  out-dl     $(gettext "Pipe Wget output into a GTK window")
  locale     $(gettext "Configure system language (root)")
  keymap     $(gettext "Configure system keymap (root)")
  tz         $(gettext "Configure system timezone (root)")
  setup      $(gettext "System initial setup (locale, keymap & timezone)")
  new-file   $(gettext "Create a new file or folder on the desktop")
  all-apps   $(gettext "Icons of all installed applications.")

EOT
}

# Su frontend GUI's
su_main() {
	text=$(gettext "Slitaz admin password")
	note=$(gettext "Please enter root password (default root) to execute:")
	yad --title="Slitaz - su" --window-icon=$icon \
		--width=520 --height=160 \
		--text="<b>$text</b>\n$note\n$SU_CMD\n" \
		--image="slitaz-menu" --image-on-top \
		--center --on-top --form $PASSWD \
		--field="`gettext "Password:"`:H" $CHECKED \
		--field="`gettext "Autosave password"`:CHK"
}

su_error() {
	text=$(gettext "Error: wrong password!")
	yad --title="Slitaz - su error" --width=520 --height=60 \
		--image="error" --image-on-top --center --on-top \
		--text="\n\t<b>$text</b>" --button="gtk-close:1"
}

# User may press cancel on download.
cancel_dl() {
	if [ "$?" == 1 ]; then
		echo "CANCEL"
		rm -f $DOWNLOADS/$(basename $url)
	fi
}

# Output a command in a GTK window
output_command() {	
	yad --text-info --title="TazBox Output" --window-icon=$icon \
		--geometry="560x210+0-24" --fore="#ffffff" --back="#000000"
}

# Logout GUI function
logout_main() {
	text=$(gettext "<b>SliTaz Logout.</b> Please choose an action:")
	yad --entry --title="SliTaz Logout" --window-icon=$icon \
		--width=440 --height=140 --text="$text" \
		--image="slitaz-menu" --image-on-top \
		--center --on-top  --entry-text \
			"`gettext \"Close X session\"` : exit" \
			"`gettext \"Reboot system\"` : reboot" \
			"`gettext \"Shutdown system\"` : halt"
}

# Generate keymap list
gen_kmap_list() {
	echo > $tmp
	cd /usr/share/kbd/keymaps/i386
	# We first need a list to sort and then use \n for Yad list.
	for i in $(find *rty *rtz dvorak -name *.map.gz)
	do
		keymap=$(basename $i)
		type=$(dirname $i)
		echo -e "$keymap|$type" >> $tmp
	done
}

# Initial Config functions
setup_main() {
	gen_kmap_list
    title=$(gettext "SliTaz Initial Setup")
    message=$(gettext "\n<big>Here you can set your preferences\nfor <b>locale, keymap and timezone</b></big>\n\n")
    locale=$(ls -1 $db | grep ^[a-z][a-z]_[A-Z][A-Z] | tr "\n" "!")
    keymap=$(cat $tmp | cut -d. -f1 | sort | tr "\n" "!")
    timezone=$(find $zi -type f | sed s,$zi,,g | tr "\n" "!")
    yad --width=500 --height=380 \
		--image=$icon --title="$title" --form --text="$message" \
		--field "Locale:CB" \
		--field "Keymap:CB" \
		--field "Timezone:CB" \
		$locale \ $keymap \ $timezone    
}

setup() {
	choices=$(setup_main)
	locale=$(echo $choices | cut -d"|" -f1)
	keymap=$(echo $choices | cut -d"|" -f2)
	timezone=$(echo $choices | cut -d"|" -f3)
	[ $locale ] && tazlocale init $locale
	[ $keymap ] && tazkeymap init $keymap
	[ $timezone ] && echo $timezone > /etc/TZ
}

# Locale functions
locale_main() {
	text=$(gettext "Language configuration")
	for locale in $(ls -1 $db | grep ^[a-z][a-z]_[A-Z][A-Z])
	do
		desc=$(grep ^title $db/$locale | cut -d '"' -f 2)
		echo -e "$locale \n $desc"
	done | \
	yad --list --title="SliTaz locale" --window-icon=$icon \
		--width=500 --height=380 --separator="" \
		--center --sticky --on-top \
		--image=preferences-desktop-locale --image-on-top \
		--text="<b>$text</b>" --print-column=1 \
		--column $(gettext "Name") --column $(gettext "Description")
}

locale() {
	locale=$(locale_main)
	# Deal with --button values
	case $? in
		1) exit 0 ;;
		*) continue ;;
	esac
	# System language configuration.
	[ "$locale" ] && tazlocale init $locale
}

# Keymap functions
keymap_main() {
	gen_kmap_list
	text=$(gettext "Keyboard configuration")
	for i in $(sort $tmp)
	do
		keymap=$(echo $i | cut -d "|" -f 1)
		type=$(echo $i | cut -d "|" -f 2)
		echo -e "${keymap%.map.gz} \n $type"
	done | \
	yad --list $opts --title="SliTaz keymap" --window-icon=$icon \
		--width=500 --height=380 --separator="" \
		--center --sticky --on-top \
		--image=input-keyboard --image-on-top \
		--text="<b>$text</b>" --print-column=1 \
		--column $(gettext "Keymap") --column $(gettext "Type")
	rm -f $tmp
}

keymap() {
	keymap=$(keymap_main)
	# Deal with --button values
	case $? in
		1) exit 0 ;;
		*) continue ;;
	esac
	# System keymap configuration
	[ "$keymap" ] && tazkeymap init $keymap
}

# TZ functions
tz_main() {
    	text=$(gettext "TimeZone Configuration")
    	for t in $(find $zi -type f | sed s,$zi,,g)
    	do
        	echo -e "$t"
    	done | \
    	yad --list --title="SliTaz TZ" --window-icon=$icon \
        	--width=500 --height=380 --separator="" \
        	--center --sticky --on-top \
        	--image=preferences-desktop-locale --image-on-top \
        	--text="<b>$text</b>" --print-column=1 \
        	--column $(gettext "Name")
}

tz() {
    	timezone=$(tz_main)
    	case $? in
        	1) exit 0 ;;
        	*) continue ;;
    	esac
    	[ "$timezone" ] && echo $timezone > /etc/TZ
}

# New file functions
newfile_main() {
	text=$(gettext "Create a new file or folder on your desktop")
	yad --entry --title="$(gettext "New file")" --window-icon=$icon \
		--text="<b>$text</b>" --width=460 --height=160 \
		--center --on-top --image=slitaz-menu --image-on-top \
		--entry-label="$(gettext "File name")" --ricon=filenew \
		--button="$(gettext "SHell script"):3" \
		--button="$(gettext "Folder"):2" \
		--button="$(gettext "File"):2" \
		--button="gtk-cancel:1"
}

newfile() {
	file=$(newfile_main)
	[ "$file" ] || exit 0
	case $? in
		3)
			cat > $HOME/Desktop/$file << EOT
#!/bin/sh
#

EOT
			chmod +x $HOME/Desktop/$file ;;
		2) mkdir -p $HOME/Desktop/$file ;;
		0) touch $HOME/Desktop/$file ;;
		1|*) exit 0 ;;
	esac
}

# All applications
all_apps() {
	yad --icons --title="$(gettext "All Applications")" \
		--compact --read-dir=/usr/share/applications \
		--window-icon=$icon --width=400 --height=400 \
		--button="gtk-close:0"
}

#
# Commands
#
case "$1" in
	su)
		# Keep command in an exported variable to be used by Yad. 4 arguments
		# should be enuff: appname --opt --opt -v /dev/sda. Nothing to do if
		# we are root.
		test $(id -u) = 0 && exec $2 $3 $4 $5
		export SU_CMD="$2 $3 $4 $5"
		# Check if a password has been saved before launching main dialog
		if [ -s $HOME/.config/slitaz/subox.conf ]; then	
			PASSWD=$(cat $HOME/.config/slitaz/subox.conf)
			CHECKED="TRUE"
		fi
		# Display the main dialog (ask for password) 
		main=$(su_main)
		# Deal with --button values and exit if cancelled to avoid erasing
		# saved password.
		case $? in
			1) exit 0 ;;
			*) continue ;;
		esac
		# Save or erase Autosaved password
		if [ $(echo $main | cut -f2 -d"|") == "TRUE" ]; then 
			echo $main | cut -f 1 -d "|" > $HOME/.config/slitaz/subox.conf
			chmod 0600 $HOME/.config/slitaz/subox.conf 
		else
			cat /dev/null > $HOME/.config/slitaz/subox.conf
		fi
		# Try to login & execute. If password is wrong execute error dialog 
		echo $main | cut -f 1 -d "|" | su -c "$SU_CMD &" || su_error ;;
	logout)
		# Logout window with actions
		main=`logout_main`
		# Deal with --button values
		case $? in
			1) exit 0 ;;
			*) continue ;;
		esac
		# Deal with $main values
		case "$main" in
			*exit) openbox --exit || jwm -exit ;;
			*reboot) reboot ;;
			*halt) poweroff ;;
		esac ;;
	out)
		# Pipe a command into a GTK window
		output_command ;;
	out-dl)
		# A tiny GTK window for Busybox wget output
		url=$2
		[ -d $DOWNLOADS ] || mkdir -p $DOWNLOADS
		busybox wget -c -P $DOWNLOADS $url 2>1 | output_command
		cancel_dl ;;
	locale)
		locale ;;
	keymap)
		keymap ;;
    tz)
        tz ;;
    setup)
		setup ;;
	boot)
		# This command is used at first boot to configure system.
		Xorg -br -quiet -nolisten tcp :1 &
		DISPLAY=:1 openbox &
		locale
		. /etc/locale.conf
		export LANG LC_ALL
		keymap
		killall Xorg 2>/dev/null ;;
	new-file)
		newfile ;;
	all-apps)
		all_apps ;;
	*)
		usage ;;
esac

exit 0
