#!/bin/bash
#SBATCH --job-name=start-rstudio
#SBATCH --partition=normal_q 
#SBATCH --nodes=1 #number of nodes
#SBATCH --ntasks-per-node=16 #maximum number of tasks per node
#SBATCH --mem=16G #memory per node
#SBATCH --time=00:10:00 #specify the runtime using HH:MM:SS 
#SBATCH --account=cbhds #replace it with your slurm account name
#SBATCH --mail-user missizxm@vt.edu #replace it with your own email address
#SBATCH --mail-type BEGIN
#SBATCH --mail-type END
#SBATCH --output=start-rstudio.%J.out
#SBATCH --error=start-rstudio.%J.err

# Specify path to container
myworkdir=$1
mytmpdir=$2
# Get the SIF
SIF=${myworkdir}/tidyverse_latest.sif

# Specify path to tmp directory created in previous section
TMPDIR=${mytmpdir}

# Load the apptainer module, you can just run module load containers/apptainer if v1.1.8 is not available
module load containers/apptainer/1.1.8

# Configure RStudio Server behavior and user credentials
node=$(hostname -s) # Get the node info
user=$(whoami)  # Get the current user's username
port=8787
cluster="tinkercliffs1"  # Set the cluster name
export APPTAINERENV_RSTUDIO_SESSION_TIMEOUT=0 # Do not suspend idle sessions.

# Set up container username and password 
export APPTAINERENV_USER=${user} 
export APPTAINERENV_PASSWORD=$(openssl rand -base64 15) 

# Print debugging information
echo "Debugging Information:"
echo "Node : ${node}"
echo "User: ${user}"
echo "Cluster: ${cluster}"
echo "Port: ${port}"
echo "Container Path: ${SIF}"
echo "Temporary Directory: ${TMPDIR}"

# Print instructions for setting up an SSH tunnel and logging into RStudio Server
echo -e "

1. SSH tunnel from your workstation using the following command (macOS, Linux and Windows PowerShell):

   ssh -N -L ${port}:${node}:${port} ${user}@${cluster}.arc.vt.edu 

   and point your web browser to http://localhost:${port}

2. Log in to RStudio Server using the following credentials:

   user: ${APPTAINERENV_USER}
   password: ${APPTAINERENV_PASSWORD}

When done using RStudio Server, terminate the job by:

1. Exit the RStudio Session (\"power\" button in the top right corner of the RStudio window)
2. Issue the following command on the login node:

      scancel -f ${SLURM_JOB_ID}
"

# Run RStudio server in a container 
# If you need to access files in multiple project directories, replace --bind ${myworkdir} with --bind project_directory_absolute_path1, path2, path3 
apptainer exec \
    -B ${myworkdir} \
    -B $TMPDIR/var/lib:/var/lib/rstudio-server \
    -B $TMPDIR/var/run:/var/run/rstudio-server \
    -B $TMPDIR/tmp:/tmp \
    $SIF \
    rserver \
    --server-user ${user} \
    --auth-none=0 \
    --auth-pam-helper-path=pam-helper \
    --auth-stay-signed-in-days=1 \
    --auth-timeout-minutes=0

echo -e "rserver exited"

exit
