#!/bin/bash -f

# Copyright © 2018-2023, Spillbox. All rights reserved.
# Property of Spillbox Inc.
# Any kind of copying or producing derivative work is prohibited without
# explicit written consent from Spillbox Inc.

#DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
case "$0" in
        ./*|/*)
            DIR="$(realpath $(dirname $0))"
            ;;
        -bash)
            echo "Do not source this file"
            return
            ;;
         *)
            tmp=$(which $0)
            DIR="$(realpath $(dirname $tmp))"
            ;;
esac

export SPILLBOX_VPN=1
export SPILLBOX_HYBRID_OPTION=hybrid
unset SPILLBOX_TRANSPORT_SERVER
unset job_manager
setup_file=$DIR/setup.sh;

if [ "${SPILLBOX_SERVER}" != "" ]; then
    export SPILLBOX_SERVER=${SPILLBOX_SERVER}
else
    if [ -f "$setup_file" ]; then
        . $setup_file
    else
        echo SPILLBOX_SERVER env not set >&2
        echo You can setup in $setup_file >&2
        exit 1
    fi
fi

if [ "${SPILLBOX_PROJECT}" == "" ]; then
    export SPILLBOX_PROJECT=default
fi
if [ "${SPILLBOX_CONFIGDIR}" != "" ]; then
    CONFIGDIR="${SPILLBOX_CONFIGDIR}/.config/spillbox"
else
    CONFIGDIR="$HOME/.config/spillbox"
fi

BASE=$(basename $0)


case "$1" in
    -l)
        exec $DIR/../splrun brun -vnclist
        ;;
    -k)
        if [ "$2" == "" ]; then
            echo "Error: VNC port number not provided" >&2
            exit 1
        fi 
        exec $DIR/../splrun brun -vnckill $2
        ;;
    create-project)
        exec $DIR/../splrun project apply ${SPILLBOX_PROJECT}
        ;;
    list-project)
        exec $DIR/../splrun project list
        ;;
    snapshot-project)
        exec $DIR/../splrun project snapshot ${SPILLBOX_PROJECT}
        ;;
    download-project)
        if [ "$2" == "" ]; then
            echo "Error: source path is not provided" >&2
            exit 1
        fi
        exec $DIR/../splrun download $2 $3
        ;;
    destroy-project)
        exec $DIR/../splrun project destroy_all ${SPILLBOX_PROJECT}
        ;;
    -p)
        if [ "$2" == "" ]; then
            echo "Error: VNC NEW PASSWORD is not provided" >&2
            exit 1
        fi
        exec $DIR/../splrun brun -vncpasswd $2
        ;;
    -sp)
        exec $DIR/../splrun brun -vncshowpasswd
        ;;
     *)  
        case "$job_manager" in
            lsf)
                export SPLAPP_VNC=1 
                exec $DIR/../lsf/bsub -I /bin/bash
                ;;
            slurm)
                export SPLAPP_VNC=1 
                exec $DIR/../slurm/srun  /bin/bash
                ;;
            uge)
                export SPLAPP_VNC=1 
                exec $DIR/../uge/qrsh  /bin/bash
                ;;
            rtda)
                export SPLAPP_VNC=1 
                exec $DIR/../rtda/nc run  /bin/bash
                ;;
            *)
                exec $DIR/../splrun brun -vnc
                ;;
        esac
esac

