#!/bin/ash
# simple GUI for x11vnc
# Copyright (C) James Budiono 2012
# License: GNU GPL Version 3 or later
#
# Rewritten from for Fatdog64 600
#
# mode of operation
# - started when server is already running - offer to terminate
# - started when server not running - if password file exist & symlink exist, start server
#   otherwise ask
# 131127 internationalisation TODO: x11vnc-doc.txt

# std localisation stanza
export TEXTDOMAIN=fatdog
. gettext.sh
# performance tweak - use "C" if there is no localisation
! [ -e $TEXTDOMAINDIR/${LANG%.*}/LC_MESSAGES/$TEXTDOMAIN.mo ] &&
! [ -e $TEXTDOMAINDIR/${LANG%_*}/LC_MESSAGES/$TEXTDOMAIN.mo ] && LANG=C

### configuration
APPTITLE="$(gettext 'x11vnc Remote Desktop Server')"
PASSWORD_FILE=$HOME/.x11vnc-password
SYMLINK_SOURCE=$(readlink -f "$0")
SYMLINK_TARGET=$HOME/Startup/${0##*/}

# run the server
run_x11vnc() {
	exec x11vnc -modtweak -xkb -clear_all -capslock -nolookup -forever -bg -passwdfile $PASSWORD_FILE
}

### main
if pidof x11vnc; then
	# already running - offer to terminate
	if Xdialog --title "$APPTITLE" --ok-label "$(gettext 'Stop Server')" --cancel-label "$(gettext 'Cancel')" \
			   --yesno "$(gettext 'x11vnc is running. Would you like to stop the server?')" 0 0; then
		killall x11vnc
		rm -f $SYMLINK_TARGET
		rm -f $PASSWORD_FILE
	fi
else
	# not running, see if we've got our symlink and password - if yes, assume we want to auto-start it.
	[ -e $SYMLINK_TARGET -a -e $PASSWORD_FILE ] && run_x11vnc
	
	# if not, ask for details
	choice=$(Xdialog --title "$APPTITLE" --stdout --help "" --menubox "$(gettext 'Please choose from the following:')" 470x159 5 \
	Onetime "$(gettext 'Start the x11vnc server this one time.')" \
	Everytime "$(gettext 'Start the x11vnc server now and at every boot.')")
	case $? in
		0) if pass=$(Xdialog --title "$APPTITLE" --stdout --password --inputbox "$(gettext 'Enter password to connect to this server')" 0 0); then
				[ -z "$pass" ] && exec "$0"
				echo $pass > $PASSWORD_FILE
			    case $choice in
					Onetime) run_x11vnc ;;
					Everytime) ln -s $SYMLINK_SOURCE $SYMLINK_TARGET; run_x11vnc ;;
			    esac
		   else 
				exec "$0"
		   fi
		   ;;
		2) defaulttexteditor /usr/share/doc/x11vnc-doc.txt &
		   exec "$0" 
		   ;;
	esac
fi

