#!/bin/sh

PATH=/usr/bin:/bin:/usr/sbin:/sbin

if [[ $# != 3 ]]
then
  echo Syntax: $0 '<hostname> <dispnum> <geometry>'
  exit 1
fi

count=1
while [ "`/sbin/runlevel`" = "unknown" ]; do
        echo "Waiting for container to finish booting."
        sleep 1
        let count++
        if (("$count" > 20)); then
                echo "Container failed to boot"
                exit 1
        fi
done

hostname=$1
dispnum=$2
geometry=$3
cookie=$(mcookie)

# Create /Xvnc and drop to the 'nobody' user.

if [[ $(id -u) == 0 ]]
then
    mkdir -p /var/lib/hubzero/Xvnc
    mkdir -p /var/log/hubzero/Xvnc
    mkdir -p /var/run/hubzero/Xvnc
    chown nobody:root /var/lib/hubzero/Xvnc
    chown nobody:root /var/log/hubzero/Xvnc
    chown nobody:root /var/run/hubzero/Xvnc
    chmod 755 /var/lib/hubzero/Xvnc
    chmod 755 /var/log/hubzero/Xvnc
    chmod 755 /var/run/hubzero/Xvnc
    cd /var/lib/hubzero/Xvnc
    echo $0: Becoming nobody.
    su -c "$0 $*" nobody
    exit $?
fi

umask 022

if [[ $(id -u) != $(id -u nobody) ]]
then
  mkdir -p ~/.vnc
  chmod go-rwx ~/.vnc
  cd ~/.vnc
fi

#
# Get the VNC password from standard input.
#
echo $0: Waiting for 8-byte vncpasswd and EOF.
dd count=1 bs=8 of=passwd-${hostname}:${dispnum}
echo "Got the vncpasswd"
chmod go-r passwd-${hostname}:${dispnum}

#
# Build an Xauthority entry for the display.
#
echo Adding auth for ${hostname}:${dispnum} and ${hostname}/unix:${dispnum}
echo add ${hostname}:${dispnum} . ${cookie} > authlist-${hostname}:${dispnum}
echo add ${hostname}/unix:${dispnum} . ${cookie} >> authlist-${hostname}:${dispnum}
cat authlist-${hostname}:${dispnum} | xauth -f Xauthority-${hostname}:${dispnum} source -

(( portnum = 5000 + ${dispnum} ))

#
# When a log file is created, make sure it is not user-readable.
#
umask 077

#
# Start the display.
#
/usr/bin/Xvnc :${dispnum} -desktop hub -geometry $geometry -auth Xauthority-${hostname}:${dispnum} \
	-depth 24  -rfbwait 30000 -rfbauth passwd-${hostname}:${dispnum} \
	-rfbport ${portnum} -co /etc/X11/rgb -pn -fp \
/usr/share/fonts/X11/misc,\
/usr/share/fonts/X11/cyrillic,\
/usr/share/fonts/X11/100dpi/:unscaled,\
/usr/share/fonts/X11/75dpi/:unscaled,\
/usr/share/fonts/X11/Type1,\
/usr/share/fonts/X11/100dpi,\
/usr/share/fonts/X11/75dpi,\
/var/lib/defoma/x-ttcidfont-conf.d/dirs/TrueType \
> /var/log/hubzero/Xvnc/Xvnc-${hostname}:${dispnum}.log 2>&1 &

#
# Record the pid of the process just started.
#
pid=$!
echo ${pid} > /var/run/hubzero/Xvnc/Xvnc-${hostname}:${dispnum}.pid

