#!/bin/bash

#========================
#  Exec KasmVNC server 
#========================

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

# We must set a password even if then KASM does not use it for user auth.
VNC_PW='placeholder'
mkdir -p "$HOME/.vnc"
PASSWD_PATH="$HOME/.kasmpasswd"
VNC_PW_HASH=$(python3 -c "import crypt; print(crypt.crypt('${VNC_PW}', '\$5\$kasm\$'));")
echo "kasm_user:${VNC_PW_HASH}:ow" > $PASSWD_PATH
chmod 600 $PASSWD_PATH

# This is used inside our custom KASM build to allow a random socket to support Singularity
if [ "x$KASMSOCK" == "xTrue" ]; then
    export SOCKET_PORT=$(( $RANDOM % 50 + 1 ))
fi


# Start Kasm VNC
/usr/local/bin/vncserver :$DESKTOP_NUMBER -depth 24 -geometry 1280x1050 -websocketPort $BASE_PORT -httpd /usr/local/share/kasmvnc/www -disableBasicAuth -FrameRate=24 -interface 0.0.0.0


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

    PSOUT=$(ps -ef | grep /usr/local/bin/Xvnc | grep auth ) 

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

	# Sleep other 10 secs before re-checking
	sleep 10

done
