#!/bin/bash

# Exec TigerVNC server 

# Set port
if [ "x$BASE_PORT" == "x" ]; then
    DESKTOP_NUMBER=0
else
    DESKTOP_NUMBER=$(($BASE_PORT-5900+1))
fi


# Set password
if [ "x$AUTH_PASS" != "x" ]; then
    echo "[INFO] Setting up VNC password..."
    mkdir -p /home/metauser/.vnc
    /opt/tigervnc/usr/bin/vncpasswd -f <<< $AUTH_PASS > /home/metauser/.vnc/passwd
    chmod 600 /home/metauser/.vnc/passwd
    export VNC_AUTH=True
else
    echo "[INFO] Not setting up any VNC password"           
fi


# Run VNC server
if [ "x$VNC_AUTH" == "xTrue" ]; then
    /opt/tigervnc/usr/bin/vncserver :$DESKTOP_NUMBER -SecurityTypes vncauth,tlsvnc -xstartup /opt/tigervnc/xstartup
else
    /opt/tigervnc/usr/bin/vncserver :$DESKTOP_NUMBER -SecurityTypes None -xstartup /opt/tigervnc/xstartup
fi


# Check if VNC is running. If it is not, exit
while true
do

    PSOUT=$(ps -ef | grep /opt/tigervnc/usr/bin/Xvnc | grep SecurityTypes) 

    if [[ "x$PSOUT" == "x" ]] ; then
        exit 1
    fi

	# Sleep other 10 secs before re-checking
	sleep 10

done
