#!/bin/sh
#
# SliTaz tiny GUI boxes for the desktop (su, logout, locale, etc)
# and as usual, please: KISS
#
# Copyright (C) 2011-2015 SliTaz GNU/Linux - GNU GPL v3
#    - Christophe Lincoln <pankso@slitaz.org>
#    - Aleksej Bobylev <al.bobylev@gmail.com>
#

. /lib/libtaz.sh
export TEXTDOMAIN='tazbox' # i18n


# Get SliTaz settings

. /etc/slitaz/slitaz.conf


# download dir (may be in a config file)

DOWNLOADS="$HOME/Downloads"


# some constants to be used inside functions

tmp='/tmp/keymap.list'
db='/usr/share/i18n/locales'
zi='/usr/share/zoneinfo/'
ztab="${zi}zone-mini.tab"
csv='/tmp/freegeoip.csv'


#
# Functions
#

usage() {
	newline; _ 'SliTaz tiny GUI boxes for the desktop'

	newline; boldify $(_ 'Usage:')
	echo "  $(basename $0) [$(_n 'command')]"

	newline; boldify $(_ 'Commands:')
	optlist "\
usage		$(_ 'Display this short help usage')
su			$(_ 'Execute a command as super-user')
logout		$(_ 'Desktop logout box with actions')
out			$(_ 'Pipe a command output into a GTK window')
out-dl		$(_ 'Pipe wget output into a GTK window')
locale		$(_ 'Configure system language (root)')
keymap		$(_ 'Configure system keymap (root)')
tz			$(_ 'Configure system timezone (root)')
setup		$(_ 'System initial setup (locale, keymap & timezone)')
new-file	$(_ 'Create a new file or folder on the desktop')
all-apps	$(_ 'Display icons of all installed applications')
notify		$(_ 'Notify user with a desktop centered box')
tazapps		$(_ 'Configure SliTaz default applications')
vnc		$(_ 'Launch a framebuffer VNC viewer')
ssh		$(_ 'Open a remote terminal')"
	newline
}


# try to find icon in .desktop files

find_icon() {
	local_desktop=$(find $HOME/.local/share/applications \
		-name ${1##*/}.desktop 2&>/dev/null | head -n1)
	system_desktop=$(find /usr/share/applications \
		-name ${1##*/}.desktop 2&>/dev/null | head -n1)
	desktop="${local_desktop:-$system_desktop}"
	[ -n "$desktop" ] && cat $desktop | sed '/\[Desktop\ Entry\]/,/^\[/!d' | \
		sed '/^Icon=/!d' | head -n1 | cut -d= -f2
}


# su frontend GUIs

su_main() {
	CMD1="${1%% *}"; CMD2="$(echo "${1#* }" | sed 's|&|&amp;|g')"
	: ${icon=$(find_icon $CMD1)}
	icon="${icon:-dialog-password}"

	yad --title="$(_n 'SliTaz admin password')" --window-icon=$icon \
		--width=520 --on-top --center \
		--image=$icon --image-on-top \
		--text="$(_n 'Please enter root password (default root) to execute:')\n
<span foreground=\"red\"><tt><b>$CMD1</b> $CMD2</tt></span>\n" \
		--form \
		--field="$(_n 'Password:'):H" $PASSWD \
		--field="$(_n 'Autosave password'):CHK" $CHECKED
}


su_error() {
	icon='dialog-error'
	yad --title="$(_n 'Error')" --window-icon=$icon \
		--width=320 --on-top --center \
		--image=$icon --image-on-top \
		--text="\n<b>$(_n 'Error: wrong password!')</b>\n" \
		--button="gtk-close:1"
}


# user may press cancel on download.

cancel_dl() {
	if [ "$?" -eq 1 ]; then
		_ "CANCEL"
		rm -f $DOWNLOADS/$(basename $url)
	fi
}


# output a command in a GTK window

output_command() {
	: ${title=$(_n 'TazBox Output')}
	: ${icon=dialog-information}

	yad --title="$title" --window-icon="$icon" \
		--geometry='600x220+0-24' --fore='#ffffff' --back='#000000' \
		--text-info --fontname=monospace --wrap $opts \
		--button='gtk-close:1'
}


# logout GUI function

logout_main() {
	icon='/usr/share/pixmaps/slitaz-icon.png'
	yad --title="$(_n 'SliTaz Logout')" --window-icon="$icon" \
		--on-top --center --height='130' \
		--image="$icon" --image-on-top \
		--text="<b>$(_n 'SliTaz Logout - Please choose an action:')</b>" \
		--always-print-result \
		--button "$(_n 'Close X session')!system-log-out:4" \
		--button "$(_n 'Reboot system')!system-reboot:3" \
		--button "$(_n 'Shutdown system')!system-shutdown:2"
}


# logout functions with auto-confirmation

logout_confirm() {
	timeout=5
	case $1 in
		exit)   action="$(_n 'Closing the X session...')";    icon='system-log-out';;
		reboot) action="$(_n 'Rebooting the system...')";     icon='system-reboot';;
		halt)   action="$(_n 'Shutting down the system...')"; icon='system-shutdown';;
		*) exit;;
	esac
	warning="$(_ 'Selected action will be executed automatically in %s seconds.' "$timeout")"
	yad --title="$(_n 'SliTaz Logout')" --window-icon="$icon" \
		--on-top --center --width='300' --image="$icon" --image-on-top \
		--text="<b>$action</b>\n\n$warning" \
		--timeout $timeout --timeout-indicator=bottom \
		--button "gtk-cancel:252" --button "gtk-ok:0"
	[ "$?" -ne 252 ] || exit 0
}


# make logout menu in the right edge of LXPanel

mkmenu() {
	# (re)make the menu button with the user log name
	dd="$HOME/.local/share/desktop-directories"; mkdir -p "$dd"
	echo -e "[Desktop Entry]\nType=Directory\nName=$(whoami)" > "$dd/user.directory"

	# check the panel config file existence, copy from default config if needed
	panels=$(find $HOME/.config/lxpanel -type f -name panel 2>/dev/null)
	if [ -z "$panels" ]; then
		mkdir -p "$HOME/.config/lxpanel"
		cp -a /etc/skel/.config/lxpanel/* "$HOME/.config/lxpanel"
	fi

	for panel in $panels; do
		conf=$(tr '\n' '`' < $panel | sed 's|Plugin|\n&|g') # each plugin on its own line
		if fgrep -q 'user.directory' "$panel"; then
			# if menu already exists - shrink it to '@@@'
			newconf=$(echo "$conf" | sed 's|.*user\.directory.*$|@@@|')
		else
			# otherwise do nothing
			newconf="$conf"
		fi
		menu=$(cat <<EOT
Plugin {
    type = menu
    Config {
        name=user.directory
        image=avatar-default
        tintcolor=#33230D
        item {
            image=system-log-out-panel
            name=$(_ 'Close X session')
            action=tazbox logout exit
        }
        item {
            image=system-reboot-panel
            name=$(_ 'Reboot system')
            action=tazbox logout reboot
        }
        item {
            image=system-shutdown-panel
            name=$(_ 'Shutdown system')
            action=tazbox logout halt
        }
    }
}

EOT
)
		# rebuild the menu: change '@@@' to the menu content
		echo "$newconf" | \
		awk -vmenu="$menu" '{if ($1=="@@@") {printf ("%s\n\n", menu)} else {print}}' | \
		tr '`' '\n' > $panel
	done
}


# 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 -type f | sed '/include/d; s|./||'); do
		echo "$(basename $i .map.gz)|$(dirname $i)" >> $tmp
	done
}


# Initial Config functions

setup_main() {
	icon='preferences-desktop-locale'
	gen_kmap_list
	locale=$(ls -1 $db 2> /dev/null | grep ^[a-z][a-z]_[A-Z][A-Z] | tr "\n" "!")
	keymap=$(cat $tmp | sort | tr "\n" "!")
	timezone=$(find $zi -type f | sed s,$zi,,g | grep -v -F '.tab' | tr "\n" "!")
	yad --title="$(_n 'SliTaz Initial Setup')" --window-icon=$icon \
		--width='500' \
		--image="$icon" --image-on-top \
		--text="<big>$(_n 'Here you can set your preferences \n for <b>locale, keymap and timezone</b>.')</big>" \
		--form \
		--field "$(_n 'Locale'):CB" $locale \
		--field "$(_n 'Keymap'):CB" $keymap \
		--field "$(_n 'Timezone'):CB" $timezone
}


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


#
# Locale functions
#

locale_main() {
	icon='preferences-desktop-locale'
	for locale in $(ls -1 $db 2> /dev/null | grep '[a-z]_[A-Z]'); do
		desc=$(fgrep -m1 title $db/$locale | cut -d'"' -f2)
		ll_CC=${locale%%@*}
		echo -e "${ll_CC##*_}\n$locale\n$desc"
	done | \
	yad --title="$(_n 'SliTaz locale')" --window-icon="$icon" \
		--width='600' --height='380' --sticky --on-top --center \
		--image="$icon" --image-on-top \
		--text="<b>$(_n 'Language configuration')</b> \
\n\n$(_ 'Tip: manage locales list by installing/removing locale packages.')" \
		--list --column="$(_n 'Flag'):IMG" --column $(_n 'Name') \
		--column $(_n 'Description') \
		--print-column='2' --separator='' \
		--button="$(_n 'Manage')!document-properties:2" \
		--button="gtk-cancel:1" --button="gtk-ok:0"
}


locale() {
	locale=$(locale_main)
	# Deal with --button values
	case $? in
		2) tazbox manage_i18n main ;;
		1) exit 0 ;;
		*) continue ;;
	esac
	# System language configuration.
	if [ "$locale" ]; then
		tazlocale $locale
		tazbox notify "$(_ 'Locale was set to %s' "$locale")" \
			preferences-desktop-locale 3
	fi
}


# Keymap functions

keymap_main() {
	icon='preferences-desktop-keyboard'
	gen_kmap_list
	for i in $(sort $tmp); do
		echo "$i" | tr '|' '\n'
	done | \
	yad --title="$(_ 'SliTaz keymap')" --window-icon=$icon \
		--width=500 --height=380 --sticky --on-top --center \
		--image=$icon --image-on-top \
		--text="<b>$(_n 'Keyboard configuration')</b>" \
		--list --column $(_n 'Keymap') --column $(_n 'Type') \
		--print-column=1 --separator=''
	rm -f $tmp
}


keymap() {
	keymap=$(keymap_main)
	# Deal with --button values
	[ "$?" -eq 1 ] && exit 0
	# System keymap configuration
	[ -n "$keymap" ] && tazkeymap $keymap
}


# Free GeoIP service
# Response: IP,CountryCode,CountryName, ...

geoip() {
	# freegeoip.net can be in the blocked hosts list. Return only correct answer or nothing
	[ ! -e $csv ] && wget -q -T3 -O - http://freegeoip.net/csv/ 2&>/dev/null | \
		grep '[0-9.]*,.*,.*,.*,.*,.*,.*,.*,[0-9.]*,[0-9.]*' > $csv
	[ -e $csv ] && cut -d, -f2 $csv
}


#
# TZ functions
#


# list of all existing available locations for country

tz_list() {
	find $zi | \
		grep -E "$(awk -F$'\t' -vv="$1" '{if ($1 == v || $2 ~ v) print $2}' $ztab | tr ' ' '|')" | \
		grep -v -E "posix|right" | \
		sed 's|.*/||g' | sort
}


# ask for confirmation only if we have what to choose

tz_suggest() {
	CountryCode=$(geoip)
	if [ -n "$CountryCode" ]; then
		if [ -n "$(tz_list $CountryCode)" ]; then
			CountryName=$(cut -d, -f3 $csv)
			yad --title="$(_ 'SliTaz TZ')" --window-icon="$icon" \
			--on-top --center \
			--image="$CountryCode" --image-on-top \
			--text="$(_ 'Suggested location:') <b>$CountryName</b>\n
$(_ 'Are you agreed?')" \
			--button='gtk-yes:0' --button='gtk-no:1'
			[ "$?" -eq 0 ] && echo $CountryCode
		fi
	fi
}


tz_select() {
	case x$1 in
	x)
		# first pass - country
		tmpcc=$(mktemp)

		for tzfile in $(find $zi -type f -regex '.*info/[ABCEIMP].*'); do
			grep -m1 $(basename $tzfile) $ztab
		done | cut -d$'\t' -f1 | sort -u > $tmpcc

		for CC in $(cat $tmpcc); do
			cat << EOT
$CC
$CC
$(grep -m1 "$CC	" ${zi}iso3166.tab | cut -d$'\t' -f2 | sed 's|\&|&amp;|g')
EOT
		done | \
		yad --title="$(_ 'SliTaz TZ')" --window-icon="$icon" \
			--width='500' --height='380' --on-top --center \
			--image="$icon" --image-on-top \
			--text="<b>$(_ 'TimeZone Configuration')</b> \
\n$(_ 'Select country and press "Forward" or manually select timezone file.') \
\n\n$(_ 'Tip: manage timezones list by installing/removing locale packages.')" \
			--list \
			--column="$(_n 'Flag'):IMG" --column=$(_n 'Code') --column=$(_n 'Country') \
			--button="$(_n 'Manage')!document-properties:4" \
			--button="$(_n 'Manual')!gtk-index:2" \
			--button="gtk-go-forward:0" \
			--button="gtk-cancel:1" --always-print-result \
			--print-column='2' --separator=''
		;;
	xindex)
		# manual selection of file with timezone info
		yad --title="$(_ 'SliTaz TZ')" --window-icon="$icon" \
			--width='500' --on-top --center \
			--image="$icon" --image-on-top \
			--text="<b>$(_ 'TimeZone Configuration')</b>\n$(_ 'Select time zone')" \
			--form --field=":FL" ${zi}UTC --separator='' | \
			sed "s|$zi||"
		;;
	*)
		# second pass - city/place
		list=$(tz_list $1)
		icon="$1"
		if [ $(echo "$list" | wc -l) != 1 ]; then
			echo "$list" | \
			yad --title="$(_ 'SliTaz TZ')" --window-icon="$icon" \
				--width='500' --height='380' --on-top --center \
				--image="$icon" --image-on-top \
				--text="<b>$(_ 'TimeZone Configuration')</b>\n$(_ 'Select location')" \
				--list --column $(_n 'Location/City') --separator=''
		else
			echo $list
		fi
		;;
	esac
}


tz() {
	icon='preferences-system-time'
	arg=$(tz_suggest)

	timezone=$(tz_select $arg)
	case $? in
		1) exit 0 ;;
		0)
			[ -n "$timezone" ] && timezone=$(tz_select "$timezone")
			[ -z "$timezone" ] && exit 0
			timezone=$(find $zi -name $timezone | grep -v -E "posix|right" | \
				sed "s|$zi||")
			;;
		2) timezone=$(tz_select "index") ;;
		4) tazbox manage_i18n main;;
	esac

	[ -z "$timezone" ] && exit 0
	echo $timezone > /etc/TZ
	export TZ=$timezone
	tazbox notify "$(_ 'TimeZone was set to %s' "$timezone")" $icon 3
	rm -f $tmpcc
}


#
# Manage i18n packages
#


# if installed

if_installed() {
	[ -d "$INSTALLED/$1" ]
}


# get package's description, install flag and sizes

desc_etc() {
	if grep -q "^$1"$'\t' "$PKGS_DB/installed.info"; then
		echo 'TRUE' >> $PKGS_LIST; echo $1 >> $ORIG_LIST
	else
		echo 'FALSE' >> $PKGS_LIST
	fi
	awk -F$'\t' -vp="$1" '
		($1==p){
			split($7, s, " ");
			printf "%s\n%s\n%s\n%s\n", $1, $4, s[1], s[2];
		}' "$PKGS_DB/packages.info" >> $PKGS_LIST
}


# remove temp

rm_temp() {
	rm -f $PKGS_LIST $ORIG_LIST $ANSWER $NEW_LIST $LIST1 $LIST2
}


# install/remove locale packages

manage_i18n() {
	PKGS_LIST=$(mktemp)
	ORIG_LIST=$(mktemp)
	ANSWER=$(mktemp)
	NEW_LIST=$(mktemp)
	LIST1=$(mktemp)
	LIST2=$(mktemp)
	PINFO="$PKGS_DB/packages.info"

	if [ ! -e "$PINFO" ]; then
		icon='dialog-warning'
		yad --title="$(_n 'Manage locale packages')" --window-icon="$icon" \
			--width='400' --on-top --center \
			--image="$icon" --image-on-top \
			--text="$(_n 'Please, recharge packages database.')" \
			--button="$(_n 'Recharge list')!view-refresh:2" \
			--button="gtk-cancel:1"

		case "$?" in
			1) rm_temp; return;;
			2) tazbox recharge;;
		esac
	fi

	tazbox notify "$(_ 'Please wait')" appointment-soon &

	for i in $(awk -F$'\t' '$1~/^locale-[a-z_A-Z]+$/{print $1}' $PINFO); do
		desc_etc $i
	done

	if [ "$1" != 'main' ]; then
		for i in $(awk -F$'\t' '$1~/^locale-[a-z_A-Z]+-extra$/{print $1}' $PINFO); do
			desc_etc $i
		done

		if if_installed libQtCore; then
			for i in $(awk -F$'\t' '$1~/^qt-locale/{print $1}' $PINFO); do
				desc_etc $i
			done
		fi

		if if_installed razorqt; then
			for i in $(awk -F$'\t' '$1~/^razorqt-locale/{print $1}' $PINFO); do
				desc_etc $i
			done
		fi

		if if_installed firefox; then
			for i in $(awk -F$'\t' '$1~/^firefox-langpack/{print $1}' $PINFO); do
				desc_etc $i
			done
		fi

		if if_installed thunderbird; then
			for i in $(awk -F$'\t' '$1~/^thunderbird-langpack/{print $1}' $PINFO); do
				desc_etc $i
			done
		fi

		if if_installed squirrelmail; then
			for i in $(awk -F$'\t' '$1~/^squirrelmail-[a-z][a-z][_-]/{print $1}' $PINFO); do
				desc_etc $i
			done
		fi

		if if_installed aspell; then
			for i in $(awk -F$'\t' '$1~/^aspell-[a-z][a-z]_?[A-Z]?[A-Z]?$/{print $1}' $PINFO); do
				desc_etc $i
			done
		fi

		OTHER_LOCALE="gnome-commander|-i18n gnome-vfs|-i18n gpa|-langpack \
		gucharmap|-i18n lxterminal|-locales lyx|-locales rox-filer|-locales \
		ufraw|-locales qupzilla|-locales"
		for i in $OTHER_LOCALE; do
			if if_installed ${i%%|*}; then desc_etc ${i/|/}; fi
		done
	fi

	icon='preferences-desktop-locale'
	cat $PKGS_LIST | \
	{
		yad --title="$(_n 'Manage locale packages')" --window-icon="$icon" \
		--width='600' --height='400' --on-top --center \
		--image="$icon" --image-on-top \
		--text="$(_n 'Check only locale packages you need and press "Install/Remove".')" \
		--list --multiple --ellipsize='END' --expand-column='3' \
		--column="$(_n 'Inst.'):CHK" --column="$(_n 'Package Name'):TEXT" \
		--column="$(_n 'Description'):TEXT" --column="$(_n 'Size'):TEXT" \
		--column="$(_n 'Installed'):TEXT" \
		--button="$(_n 'Recharge list')!view-refresh:4" \
		--button="$(_n 'Install/Remove')!gtk-execute:2" \
		--button="gtk-cancel:1" \
		--print-all
	} > $ANSWER

	case "$?" in
		1) rm_temp; exit 0;;
		4) tazbox recharge; rm_temp; tazbox manage_i18n; exit 0;;
	esac

	grep -e 'TRUE' $ANSWER | cut -d'|' -f2 > $NEW_LIST

	# check difference between ORIG_LIST and NEW_LIST
	sort -o $LIST1 $ORIG_LIST
	sort -o $LIST2 $NEW_LIST
	DIFF=$(diff $LIST1 $LIST2 | sed '/---/d;/+++/d;/@@/d')
	if [ -z "$DIFF" ]; then rm_temp; exit 0; fi

	# output log to gtk window
	title="$(_n 'TazPkg log')"; icon='system-software-update'; opts='--tail'
	{
		for pkg in $(echo "$DIFF" | grep -e '^-' | sed 's|^-||g'); do
			_ 'REMOVE: %s' "$pkg"
			yes | tazpkg -r $pkg --output='raw'
		done
		for pkg in $(echo "$DIFF" | grep -e '^+' | sed 's|^+||g'); do
			_ 'INSTALL: %s' "$pkg"
			tazpkg -gi $pkg --output='raw'
		done
		echo -e "\n\n$(_n 'Done!')\n"
	} | output_command
	rm_temp
}



# New file functions

newfile_main() {
	icon='document-new'
	yad --title="$(_n 'New file')" --window-icon="$icon" \
		--width='460' --height='160' --on-top --center \
		--image="$icon" --image-on-top \
		--icon="$icon" \
		--text="<b>$(_n 'Create a new file or folder on your desktop')</b>" \
		--entry --entry-label="$(_n 'File name')" \
		--ricon='edit-clear' \
		--always-print-result \
		--button="$(_n 'SHell script')!application-x-shellscript:4" \
		--button="$(_n 'Folder')!folder:3" \
		--button="$(_n 'File')!empty:2" \
		--button='gtk-cancel:1'
}


newfile() {
	file=$(newfile_main)
	ret=$?
	[ -z "$file" ] && exit 0
	case $ret in
		4)
			cat > "$HOME/Desktop/$file" << EOT
#!/bin/sh
#

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


# All applications

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


# Ask root permissions for system settings

ask_root() {
	if [ "$(id -u)" -ne 0 ]; then
		exec tazbox su $0 $@
		exit 0
	fi
}


vnc_main() {
	icon='video-display'
	yad --title="$(_n 'Framebuffer VNC viewer')" --window-icon="$icon" \
		--width='250' --height='160' --on-top --center \
		--image="$icon" --image-on-top --icon="$icon" \
		--form \
		--text="<b>$(_n 'Remote display connection')</b>" "localhost 5900" \
		--field="$(_n 'VNC Server')" \
		--field="$(_n 'Via a SSH tunnel'):CHK" \
		--always-print-result \
		--button="$(_n 'On this console'):1" \
		--button="$(_n 'In a new console'):0"
}


ssh_main() {
	icon='xterm'
	yad --title="$(_n 'Remote connection')" --window-icon="$icon" \
		--width='250' --height='180' --on-top --center \
		--image="$icon" --image-on-top --icon="$icon" \
		--form \
		--text="<b>$(_n 'Remote terminal connection')</b>" "user@host:port" \
		--field="$(_n 'Server')" \
		--field="$(_n 'Password'):H" \
		--field="$(_n 'SSH Keys'):MFL" \
		--field="$(_n 'SSH Proxy')" \
		--field="$(_n 'Telnet protocol (instead of SSH)'):CHK" \
		--always-print-result
}


video() {
	icon='video-x-generic'

	# Get switchs
	tazwebargs="--notoolbar"
	while true ; do
		case "$1" in
		--fullscreen) 	tazwebargs="$tazwebargs --kiosk"
				dpmstimeout=$(xset q | grep timeout | cut -d' ' -f5) ;;
		--loop)		loop="loop" ;;
		*) break
		esac
		shift
	done

	# Get filename
	[ "$1" ] && file="$PWD/$(basename "$1")"
	[ "${1:0:1}" = "/" ] && file="$1"
	[ -s "$file" ] || file="$(yad --file --width='600' --height='500' --add-preview \
		--window-icon $icon --title "$(_ 'Select the video file')" --center \
		--file-filter="$(_ 'All video files')|*.mp4 *.m4v *.webm *.ogg *.ogv *.flv *.avi *.3gp" \
		--file-filter="$(_ 'All files')|*")"
	[ -s "$file" ] || return

	# Extra parameters
	text=
	attr='autoplay="true"'
	for i in jpg jpeg ; do
		[ -s "${file%.*}.$i" ] &&
		attr="poster=\"file://${file%.*}.$i\"" && break
	done
	IFS=$'\n'
	for i in ${file%.*}_${LANG%%[._]*}.vtt ${file%.*}.vtt ; do
		[ -s $i ] && text="
<track kind=\"captions\" src=\"file://$i\" srclang=\"${LANG%%[._]*}\" default>"
	done

	# Build the html5 page
	tmp=/tmp/video-player-$$.html
	cat > $tmp <<EOT
<html>
<head>
	<meta charset="UTF-8">
	<title>$(basename "$file")</title>
	<style>
		body{background:#000;margin:0}
		a{color:#29F}
		div{color:#FFF;position:absolute;bottom:2em;left:0;right:0;text-align:center}
	</style>
</head>
<body>
<video width="100%" height="100%" src="file://$file" controls $attr$loop>$text
<div>$(_ 'Unsupported video file format.')<br>
$(IFS=$'\n'; _ 'Retry with %s, %s, %s, %s, %s or %s.' \
	$(printf '<a href="http://127.0.0.1:82/user/pkgs.cgi?info=%s">%s</a>\n' \
	vlc VLC   gnome-mplayer 'GNOME MPlayer'   mplayer MPlayer   gxine gxine   xine-ui xine   ffplay ffplay))
</div>
</video>
</body>
</html>
EOT
	unset IFS
	[ -n "$dpmstimeout" ] && xset dpms 0 0 0 s 0 0
	tazweb $tazwebargs file://$tmp || browser file://$tmp
	[ -n "$dpmstimeout" ] && xset dpms $dpmstimeout $dpmstimeout $dpmstimeout s $dpmstimeout $dpmstimeout
	rm -f $tmp
}


newvt()
{
	ask_root newvt $@ || return
	openvt -sw $@
	deallocvt
}


vnc() { 
	server=$(vnc_main)
	status=$?
	# Deal with --button values
	[ "$server" ] || return
	case "$server" in
	*TRUE\|)	fbvnc=sshfbvnc ;;
	*)		fbvnc=fbvnc ;;
	esac
	case "$status" in
	1)	$fbvnc ${server%%|*} ;;
	0)	newvt $fbvnc ${server%%|*} ;;
	esac
}


ssh() { 
	IFS='|'; set -- $(ssh_main) ; unset IFS
	export TERM=sakura; [ "$(which $TERM)" ] && XTERM=$TERM || XTERM=xterm
	[ -n "$2" ] && export DROPBEAR_PASSWORD="$2"
	s=${1#*@}; k="${3:+-i ${3//!/ -i }}"
	case "$4$5" in
	TRUE)	$XTERM -e "telnet ${s/:/ }" ;;
	*RUE)	dbclient $k -B $s $4 ;;
	*)	export DBPROXY="$4"; sshx $k $1 ;;
	esac
}


#
# Commands
#

case "$1" in
	su)
		shift
		# Don't show dialog if we are root
		[ "$(id -u)" -eq 0 ] && exec "$@"
		SU_CMD="$@"
		SUBOX_CONF="$HOME/.config/slitaz/subox.conf"

		# Check if a password has been saved before launching main dialog
		if [ -s "$SUBOX_CONF" ]; then
			PASSWD="$(cat $SUBOX_CONF)"
			CHECKED='TRUE'
		fi

		# Display the main dialog (ask for password)
		main="$(su_main "$SU_CMD")"

		# Deal with --button values and exit if cancelled to avoid erasing
		# saved password.
		[ "$?" -eq 1 ] && exit 0

		# Save or erase Autosaved password
		if [ $(echo "$main" | cut -d"|" -f2) = 'TRUE' ]; then
			echo "$main" | cut -d"|" -f1 > $SUBOX_CONF
			chmod 0600 $SUBOX_CONF
		else
			cat /dev/null > $SUBOX_CONF
		fi

		# Try to login & execute. If password is wrong execute error dialog
		SU_CMD_QUOTED="$(echo "$SU_CMD" | sed 's|&|\\&|g')"
		echo $main | cut -d"|" -f1 | su -c "$SU_CMD_QUOTED &" || su_error
		;;

	logout)
		# Logout window with actions
		if [ -n "$2" ]; then
			answer="$2"
			logout_confirm $answer
		else
			logout_main; answer=$?
		fi

		# Deal with --button values
		# DE and WM started with a custom -session script should export
		# XDG_CURRENT_DESKTOP
		case $answer in
			4|exit)
				case $XDG_CURRENT_DESKTOP in
					LXDE)
						[ -n "$_LXSESSION_PID" ] && kill $_LXSESSION_PID
						[ "$DESKTOP_SESSION" = 'compiz' ] && killall compiz
						openbox --exit ;;
					openbox) openbox --exit ;;
					compiz) killall compiz ;;
					*)
						# Try to kill other WM that dont set XDG var.
						jwm -exit 2>/dev/null ;;
				esac ;;
			3|reboot)
				reboot || reboot -f ;;
			2|halt)
				poweroff ;;
		esac
		;;

	out)
		# Pipe a command into a GTK window
		sed 's|\[.m||g; s|\[[0-9][0-9]*G|	|g' | output_command
		;;

	out-dl)
		# A tiny GTK window for Busybox wget output
		url="$2"; opts='--tail --button=gtk-cancel:1'
		icon='folder-download'; title="$(_ 'Downloading...')"
		[ -d $DOWNLOADS ] || mkdir -p $DOWNLOADS
		busybox wget -c -P $DOWNLOADS $url 2>&1 | output_command
		cancel_dl
		;;

	locale)
		ask_root $@ && locale
		;;

	keymap)
		ask_root $@ && keymap
		;;

	tz)
		ask_root $@ && tz
		;;

	manage_i18n)
		ask_root $@ && manage_i18n $2
		;;

	recharge)
		ask_root $@; opts='--on-top'; output=raw tazpkg recharge | output_command
		;;

	setup)
		ask_root $@ && setup
		;;

	new-file)
		newfile
		;;

	all-apps)
		all_apps
		;;

	notify|-n)
		# On screen notification box.
		icon="$3"
		time="$4"
		[ -z "$icon" ] && icon='dialog-information'
		[ -z "$time" ] && time='4'
		yad --width='520' --height='80' --timeout="$time" --timeout-indicator='right' \
			--on-top --center --no-buttons --borders='12' --undecorated \
			--skip-taskbar --image="$icon" --image-on-top --text="<b>$2</b>"
		;;

	tazapps)
		# Default applications configuration script. System wide config file
		# is /etc/slitaz/applications.conf and each user can have personal
		# settings. System wide for root and personal config for user.
		export CONFIG="$HOME/.config/slitaz/applications.conf"
		if [ "$(id -u)" -eq 0 ]; then
			[ ! -f $CONFIG ] || mv -f $CONFIG /etc/slitaz/applications.conf
			export CONFIG='/etc/slitaz/applications.conf'
		fi

		for a in FILE_MANAGERS BROWSERS EDITORS TERMINALS WINDOW_MANAGERS; do
			eval $(expr $a=$(echo $(LC_ALL=C tazx get-applist ${a%%S} \
			only-installed yad) | sed 's/ /!/g ; s/!!//g; s/ //g'))
		done

		# Missing file was created by slitaz_apps_conf function from tazx
		. $CONFIG

		icon='preferences-desktop-default-applications'
		eval $(yad --title="$(_n 'SliTaz default applications')" \
			--window-icon="$icon" --image="$icon" --image-on-top \
			--text="<b>$(_n 'SliTaz default applications configuration')</b>" \
			--form \
			--field="$(_n 'File manager:'):CBE" "$FILE_MANAGERS" \
			--field="$(_n 'Web browser:'):CBE" "$BROWSERS" \
			--field="$(_n 'Text editor:'):CBE" "$EDITORS" \
			--field="$(_n 'Terminal:'):CBE" "$TERMINALS" \
			--field="$(_n 'Window manager:'):CBE" "$WINDOW_MANAGERS" | \
			awk -F'|' '{printf "FILE_MANAGER=\"%s\"\nBROWSER=\"%s\"\nEDITOR=\"%s\"\
TERMINAL=\"%s\"\nWINDOW_MANAGER=\"%s\"\n", $1, $2, $3, $4, $5}')

		sed '/FILE_MANAGER=/s|"\([^"]*\)"|"'$FILE_MANAGER'"|; \
			/BROWSER=/s|"\([^"]*\)"|"'$BROWSER'"|; \
			/EDITOR=/s|"\([^"]*\)"|"'$EDITOR'"|; \
			/TERMINAL=/s|"\([^"]*\)"|"'$TERMINAL'"|; \
			/WINDOW_MANAGER=/s|"\([^"]*\)"|"'$WINDOW_MANAGER'"|' \
			-i $CONFIG
		;;

	gpl)
		yad --title='GNU General Public License' --window-icon='text-x-copying' \
			--geometry='650x500' \
			--image='/usr/share/pixmaps/gpl3.png' --image-on-top \
			--center \
			--text-info \
			--fontname='monospace' \
			--button 'OK' < /usr/share/licenses/gpl.txt
		;;

	ssh)
		ssh
		;;

	vnc)
		vnc
		;;

	video)
		shift
		video "$@"
		;;

	newvt)
		$@
		;;

	mkmenu) $@ ;;

	*)
		usage
		;;
esac

exit 0
