#!/bin/sh
#
# @package      hubzero-mw-session
# @file         startxvnc
# @author       Rick Kennell <kennell@purdue.edu>
# @author       Nicholas J. Kisseberth <nkissebe@purdue.edu>
# @author       Pascal Meunier  <pmeunier@purdue.edu>
# @copyright    Copyright (c) 2005-2015 HUBzero Foundation, LLC.
# @license      http://opensource.org/licenses/MIT MIT
#
# Copyright (c) 2005-2015 HUBzero Foundation, LLC.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# HUBzero is a registered trademark of HUBzero Foundation, LLC.

set -e

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
		count=$(($count+1))
        if [ "$count" -gt 99 ]; then
                echo "Container failed to boot"
                exit 1
        fi
done

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

# Create runtime Xvnc directories and drop to the 'nobody' user.

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

umask 022

if [ $(id -u) != $(id -u nobody) ]
then
  mkdir -p ~/.vnc
  chmod go-rwx ~/.vnc
  logdir=~/.vnc
  rundir=~/.vnc
else
  logdir=/var/log/Xvnc
  rundir=/var/run/Xvnc
fi

cd ${rundir}

#
# 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"
# commented out to support Jupyter
# chmod go-r passwd-${hostname}:${dispnum}
chmod a+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

fontpath=""
for i in /usr/share/fonts/X11/misc \
  /usr/share/fonts/X11/100dpi \
  /usr/share/fonts/X11/75dpi \
  /usr/share/fonts/X11/Type1 \
  /usr/share/fonts/X11/cyrillic \
  /usr/share/fonts/truetype/freefont \
  /usr/share/fonts/truetype/msttcorefonts \
  /usr/share/fonts/truetype/ttf-bitstream-vera \
  /usr/share/fonts/truetype/ttf-dejavu \
  /usr/share/fonts/truetype/ttf-liberation \
  /usr/share/fonts/truetype/unifont \
  /var/lib/defoma/x-ttcidfont-conf.d/dirs/TrueType \
 ; do
  if test -d "$i"; then 
      #if test ! -f "$i/fonts.scale"; then
      #	echo "$i/fonts.scale missing"
      #fi

      if test -f "$i/fonts.dir"; then
      	if test "x${fontpath}" = "x"; then 
	  fontpath="$i"
      	else 
	  fontpath="$fontpath,$i"
      	fi
      #else
      #  echo "$i/fonts.dir missing, not adding to font path"
      fi
  #else
  #	echo "$i missing, not adding to font path"
  fi
 
done

#
# Start the display.
#

# 5/2018:
# Xtigervnc based on Xorg Server >= 1.17 does not listen on tcp
# by default. So we do a version check and add the flag to
# listen accordingly. We also disable inet6 to suppress some
# error messages about unavailability in some containers

if [ -f /usr/bin/Xtigervnc ]; then
XVNC=/usr/bin/Xtigervnc
XVNC_EXTRA_ARGS="-nolisten inet6"
XSERVER_VERSION=`/usr/bin/Xtigervnc -help 2>&1 | grep "X server release" | cut -f5 -d' ' | cut -c1-3`
if [ "${XSERVER_VERSION}" -gt  "116" ]
then
    XVNC_EXTRA_ARGS="-listen tcp ${XVNC_EXTRA_ARGS}"
fi
elif [ -f /usr/bin/Xvnc4 ]; then
XVNC=/usr/bin/Xvnc4
elif [ -f /usr/bin/Xtightvnc ]; then
XVNC=/usr/bin/Xtightvnc
elif [ -f /usr/bin/Xvnc ]; then
XVNC=/usr/bin/Xvnc
else
XVNC=/usr/bin/Xvnc
fi

${XVNC} :${dispnum} ${XVNC_EXTRA_ARGS} -desktop hub -geometry $geometry -auth Xauthority-${hostname}:${dispnum} \
	-depth 24  -rfbwait 30000 -rfbauth passwd-${hostname}:${dispnum} \
	-rfbport ${portnum} -pn -fp ${fontpath} > ${logdir}/Xvnc-${hostname}:${dispnum}.log 2>&1 &

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