#!/bin/bash

### NOTE TO USER, FIRST TIME: 
## in shell run 
##  The `mini` refers to the script, not to the RBOX
#  sudo ln ~/git/RBoxScripts/rbox_mini.sh /usr/bin/RBox
#  sudo ln /usr/bin/RBox /usr/bin/rbox
#
#  Then to use: 
#    rbox MyNewSessionName
#  Then, once in screen, 
#    execute  RR 


## TODO:  Reconnect is off.  Specifically because of the time.  Als, adding an extra R_ somewhere

rUser="rstudio"
remoteStartingDir="~$rUser/git"

echo "remote is $remoteStartingDir"


if [ -z "$1" ]; then
  sessionName="Session"
else 
  sessionName="$1"
fi

##  Add Date Stamp
# sessionName=""$sessionName"_$(date +"%a-%b-%d_%I%M-%p")"
# Temporarilly taking this out bc it will mess up with resumes

sessionName="R_$sessionName"

## ssh login, then exeecute screen with new session
echo
echo
echo "======================================================================"
echo "Logging in to RBox and starting session '$sessionName'"
echo "======================================================================"
sleep 0.6

# su_Rcmd="sudo su -c \\\"cd $remoteStartingDir; R\\\" -s /bin/bash rstudio"
# screenCmd1="screen -dmS $sessionName \"$su_Rcmd\""
# screenCmd2="screen -r -t $sessionName"
#    
# msg_sessEnd='R Session is over and SSH will now close'
# fullRemoreCmd="$screenCmd1; $screenCmd2; echo $msg_sessEnd; sleep 2"

screenCmd="screen -dR $sessionName"
ssh -t ubuntu@107.20.192.2 "$screenCmd"

echo
echo "======================================================================"
echo 'RBox sessions has ended. You are back where you were when you started.'
echo "======================================================================"

exit 0