#!/bin/sh
# vnc: (rustic) VNC management
# Hacked for bash under hacklin.sh
# Thank you again Michelle Andreoli.
#  from the original by M. Andreoli
# The elegance is his, the mistakes are mine.
# T. Loveall 04/24/01, email: loveall@qwest.net
#set -x

# check for a running vnc pid
pid="`cat /var/run/vnc.pid 2>/dev/null`"

#--------------
# Syntax
#-------------

case Z$1Z in
Z-hZ|ZZ) # help
cat <<END

VNC (rustic) management:

	vnc [-h]		{ this } 
	vnc start		{ start VNC server }	
	vnc stop		{ stop VNC server }	
	vnc status		{ print VNC server status }	
	vnc host:display	{ connect to another VNC server }

END
	exit
	;;
ZstopZ) # kill
	if [ -z "$pid" ] ; then
		echo "Xvnc not running."
	else
		echo "Shutting down Xvnc server pid $pid ..."
		kill -9 $pid;
		rm /var/run/vnc.pid
	fi
	exit
	;;
ZstatusZ) # status
	if [ -z "$pid" ] ; then
		echo stopped.	
	else
		echo "Xvnc running as pid $pid"
	fi
	exit
	;;
ZstartZ)
	;;
*)
	if [ -z "$DISPLAY" ]; then
		# the SVGA viewer
		svncviewer $@ # compile and supply your own
	else
		# the X viewer
		vncviewer $@ # compile and supply your own
	fi
	exit
	;;
esac

#-------------
# Environment
#--------------

XFONTS=/usr/X11R6/lib/X11/fonts/misc/,/usr/X11R6/lib/X11/fonts/75dpi/
LOG=/var/log/vnc.log

# place holder, not implemented.
JAVA=/usr/vnc/java

#---------------
# functions
#---------------

# Use a default since there 'can be only one'
 
GetDisplayNumber()
{
#set -- `nc -z -vv localhost 5900-5920 2>&1 | rgrep open`
#last=$3

if [ -z "$last" ] ; then
	# :1 as default (:0 is for X)
	display=1
else
	display=$(( $last - 5899))
fi
echo $display
}

# X are running?
X_running=
[ "$DISPLAY" ] && X_running=yes

display=`GetDisplayNumber`
host=$HOSTNAME
RFBport=$((5900 + $display))
HTTPport=$((5800 + $display))
export DISPLAY="$host:$display"
export VNCDESKTOP="VNC hacklin "

#-------------------
# Start Xvnc server
#-------------------

echo "Starting VNCserver on display $DISPLAY."

# check for valid passwd file
if [ ! -f /root/.vnc/passwd ]; then
  echo You MUST have a password to access Xvnc.
  echo Please enter a 6 character or longer password and
  echo " then log in remotely with a _clean_ vncviewer startup."
  echo " After entering the password in vncviewer _then_ save connection info."
  while [ ! -f /root/.vnc/passwd ] 
  do
    vncpasswd
  done
fi

LD_LIBRARY_PATH=/usr/X11R6/lib \
Xvnc :$display -desktop "$VNCDESKTOP" \
-httpd $JAVA \
-rfbwait 120000 \
-rfbport $RFBport \
-fp $XFONTS \
-geometry 800x600 \
-rfbauth /root/.vnc/passwd \
-co /usr/X11R6/lib/X11/rgb > $LOG 2>&1 &

pid="$!"
echo $pid > /var/run/vnc.pid

echo "VNCserver process id: $pid"
echo "VNCserver TCP ports: $RFBport(vnc), $HTTPport(http)."

sleep 3

if [ -x ~/.vnc/xstartup ] ; then
	echo "Starting X clients."
	~/.vnc/xstartup 2>/dev/null &
else
	echo "No X clients started."
fi

(
cat <<END

You can browse this display using a suitable
VNC Windows/UNIX client, using DISPLAY=$DISPLAY.

Have fun!
END
) 1>&2
