echo ""
echo "Wellcome to CSUC HPC VNC  forwarding tool. Please follow the instructions:" 
echo""


read -p "Please, select your CSUC HPC UserName : " user


echo "--------------------------------------------"

echo "Please Selec the interactive  VNC job(Please wait)"
echo ""
ssh -XC -p2122 $user@hpc.csuc.cat squeue  -p gpu  -u $user 
echo ""

read -p "Enter JOBID(First column) : " JOBID
NODE=`ssh -XC -p2122 $user@hpc.csuc.cat squeue -h -p gpu -u $user -j $JOBID --format="%R"`


case $NODE in
pirineusgpu1)
X=0
;;
pirineusgpu2)
X=1
;;
pirineusgpu3)
X=2
;;
pirineusgpu3)
X=3
esac

echo "---------------------------------------------"


echo "Please, select the number of your VNC session (X DIPLAY FIELD) in the following list(Please wait):"
echo ""
ssh -XC -p2122 $user@hpc.csuc.cat  ssh 192.168.19.8$X /prod/tools/turbovnc/2.1.1/bin/vncserver -list

echo ""

read -p "Enter SESSION( ONLY THE NUMBER ON X DIPLAY FIELD ) : " NUM


echo "-----------------------------------------------"

read -p "Please, select a free local port to forward on your computer(for example 50001) : " LOCPORT 


echo "Executing 'ssh -XC -p2122 -fN -L $LOCPORT:192.168.19.8$X:590$NUM $user@hpc.csuc.cat'"

COMMAND=`echo "ssh -XC -p2122 -fN -L $LOCPORT:192.168.19.8$X:590$NUM $user@hpc.csuc.cat"`
ssh -XC -p2122 -fN -L $LOCPORT:192.168.19.8$X:590$NUM $user@hpc.csuc.cat

echo ""
echo "Now you can start a vnc sessiun connecting to localhost:$LOCPORT . Remember use your VNC password(which you typed on first vncserver launch."
echo ""
pid=`ps -ef | grep "$COMMAND" | grep -v "grep" | awk '{print $2}' `

if [ x$pid = "x" ]
then
	echo "Unable to create port,please check your choices or contact your local administrators"
else
	echo "Youn can kill the tunnel typing 'kill -9 $pid'"
fi
