#!/bin/bash
if [ $# -ge 1 ]; then
    echo Usage: $0
    echo Environment variable VSCODE_PATH points to the absolute path
    echo of the code server executable.
    echo default: /usr/lib/code-server/bin/code-server
    echo
    echo Environment variable CONTAINER_PREFIX. Singularity command prefix
    echo to run the code server. e.g.
    echo export CONTAINER_PREFIX="singularity run --pid -B /opt,/lib64,/usr,/share,/etc/profile.d,/etc/ld.so.cache --env PATH=/usr/bin:/opt/skyformai/bin /share/apps/containers/rocky8.sif"
    exit 1
fi

if [ -z "$CB_ALLOCATION" ]; then
    echo Cannot run outside of AIP
    exit 1
fi

if [ -z $VSCODE_PATH ]; then
    VSCODE_PATH=/usr/lib/code-server/bin/code-server
fi
port=$(echo $CB_ALLOCATION | awk -F '"Port":' '{print $2}' | cut -d'}' -f1 | cut -d',' -f1)
# ip=$(hostname -I | awk {'print $1}')
ip=$(grep $(hostname -s) $CB_ENVDIR/hosts | awk '{print $1}')
token=$(echo $RANDOM | md5sum | head -c 32)
if grep -q ^pp $CB_ENVDIR/vncsub.yaml; then
    message="/vs/$ip/16000/code.html?password=$token&port=$port"
else
    message="http://$ip:16000/code.html?password=$token&port=$port"
fi
cpost -d "$message" $CB_JOBID > /dev/null 2>&1
export NODE_TLS_REJECT_UNAUTHORIZED=0
PASSWORD=$token exec $CONTAINER_PREFIX $VSCODE_PATH --disable-update-check --bind-addr=0.0.0.0:$port
