#!/bin/bash
if [ $# -ge 1 ]; then
    echo Usage: $0
    echo Environment variable RSTUDIO_PATH points to the top directory
    echo of rstudio-server, default: /usr/lib/rstudio-server
    echo
    echo Environment variable R_PATH points to the absolute path of
    echo the R executable, default: /usr/bin/R
    echo e.g. R_PATH=/share/apps/python/lib/R/bin/R
    echo
    echo Environment variable R_LD_PATH points to the absolute path of
    echo additional LD_LIBRARY_PATHs for RStudio Sessions, default: NULL
    echo e.g. R_LD_PATH=/share/apps/anaconda3/envs/JupyterLab4.0.7/lib
    echo
    echo Environment variable CONTAINER_PREFIX. Singularity command prefix
    echo to run the Rstudio. 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" ] || [ -z $CB_JOBID ]; then
    echo This script can only run in AIP
    exit 1
fi
workingdir=$HOME/.local/share/rstudio
if [ ! -d $workingdir ]; then
    mkdir -p $workingdir
fi

if [ -z $RSTUDIO_PATH ]; then
    RSTUDIO_PATH=/usr/lib/rstudio-server
fi

if [ -z $R_PATH ]; then
    R_PATHCONF=""
else
    R_PATHCONF="rsession-which-r=$R_PATH"
fi

# delete conf files older than 30 days
find $workingdir -type f -name 'rserver.conf.*' -mtime +30 -exec rm "{}" \;

port=$(echo $CB_ALLOCATION | awk -F '"Port":' '{print $2}' | cut -d'}' -f1 | cut -d',' -f1)
ip=$(grep -w $(hostname -s) $CB_ENVDIR/hosts | awk '{print $1}')

cat <<EOF > $workingdir/database.conf
provider=sqlite
directory=$workingdir
EOF

PASSWORD=$(tr -dc 'A-Za-z0-9_' </dev/urandom | head -c 32)

cat <<EOF > $workingdir/auth
#!/bin/bash
read -s -p "Password: " PASSWORD

if [ "$USER" == "\$1" ] && [ "\$RSTUDIO_PASSWORD" == "\$PASSWORD" ]; then
    echo "Successful authentication"
    exit 0
else
    echo "Invalid authentication"
    exit 1
fi
EOF
chmod +x $workingdir/auth

cat <<EOF > $workingdir/rserver.conf.$CB_JOBID
server-working-dir=$workingdir
server-data-dir=$workingdir
server-user=$USER
www-address=0.0.0.0
www-port=$port
www-root-path=/aj/$ip/$port/
database-config-file=$workingdir/database.conf
auth-none=0
auth-pam-helper-path=$workingdir/auth
auth-encrypt-password=0
auth-timeout-minutes=0
auth-stay-signed-in-days=30
$R_PATHCONF
EOF

if [ ! -z $R_LD_PATH ]; then
   echo "rsession-ld-library-path=$R_LD_PATH" >> $workingdir/rserver.conf.$CB_JOBID
fi

cpost -d "/aj/$ip/16000/rstudio.html?port=$port&username=$USER&password=$PASSWORD" $CB_JOBID > /dev/null 2>&1

RSTUDIO_PASSWORD=$PASSWORD exec $CONTAINER_PREFIX $RSTUDIO_PATH/bin/rserver --config-file $workingdir/rserver.conf.$CB_JOBID
