#!/bin/bash

#Copyright 2016 California Institute of Technology

#You should have received a copy of the licensing terms for this software included 
#in the file “LICENSE” located in the top level directory of this package.
#If you did not, you can view a copy at http://dcc.ligo.org/M1500244/LICENSE

# cleanup the ssh master and temp folder
function cleanup {
    if [ "x$SOCK" != "x" ]; then
        echo "Shutting down encrypted tunnel"
        ssh -S "$SOCK" -O exit -l $USERNAME $GATEWAY
    fi
    if [ -d "$SOCKDIR" ]; then
        echo "Removing temporary directories"
        rm -rf "$SOCKDIR"
    fi
    exit $RETVAL
}

# help message
help() {
    echo "$0 creates a connection to the LIGO remote access read-only EPICS gateways at the sites,"
    echo "sets up the environment, and launches a command with the evironment setup to use the EPICS"
    echo "gateway for the selected site."
    echo
    echo "By default it launches /bin/bash."
    echo
    echo "Usage: $0 [options] [site] [command]"
    echo
    echo "Where site is one of LHO or LLO (not case does not matter)"
    echo
    echo "Options:"
    echo "-h - this help information"
    echo "-u username - Your LIGO.ORG username (please specify this if your system username is not the same as your LIGO.ORG username)"
    echo
    echo "For users wishing to verify the ssh fingerprint of lhoepics"
    echo "the ssh key fingerprints are:"
    echo 
    echo "10:a9:0d:e5:05:b6:77:2d:d3:4a:a7:77:c7:5d:bf:1e ECDSA"
    echo "d4:05:74:2b:41:96:b4:a1:54:b3:a7:12:44:b0:98:e7 RSA"
    echo "87:6e:cd:4c:fb:9d:c4:cc:71:79:6d:0e:81:12:84:cc DSA"
    echo "6a:57:88:45:e9:c4:35:c5:05:c6:ee:cc:30:3f:c8:fc ED25519"
    echo
    echo
    echo "For users wishing to verify the ssh fingerprint of lloepics"
    echo "the ssh key fingerprints are:"
    echo 
    echo "e9:ad:a0:26:1c:04:14:6b:eb:5c:7e:32:d3:5e:2c:17 ECDSA"
    echo "24:43:02:c2:ea:87:2c:2c:8d:cf:ee:f0:2a:84:93:88 RSA"
    echo "a5:ed:eb:31:5f:e4:3f:a0:ac:0d:20:7e:c5:88:02:fa DSA"
    exit $RETVAL
}

GATEWAY=lhoepics.ligo-wa.caltech.edu

IFO=
ifo=
site=
SITE=

extract_site() {
	if [ -z "$1" ]; then
		help
	fi
	site=`echo $1 | tr '[:upper:]' '[:lower:]'`
	SITE=`echo $1 | tr '[:lower:]' '[:upper:]'`

	case "$SITE" in
		"LHO")
			GATEWAY=lhoepics.ligo-wa.caltech.edu
			IFO="H1"
			ifo="h1"
		;;
		"LLO")
			GATEWAY=lloepics.ligo-la.caltech.edu
			IFO="L1"
			ifo="l1"
		;;
		*)
		help
		;;
		esac
}

SOCKDIR=
SOCK=
RETVAL=1

USERNAME=$USER

while getopts ":hu:" OPT; do
    case $OPT in
        h)
        RETVAL=0
        help
        ;;
        u)
            USERNAME=$OPTARG
            shift $((OPTIND-1))
        ;;
        :)
        help
        ;;
    esac
done
#echo "Args = $@ after parsing"
extract_site $@
echo "IFO = $IFO"
echo "ifo = $ifo"
echo "SITE = $SITE"
echo "site = $site"
echo "GATEWAY = $GATEWAY"
shift 1
#echo "Args = $@"


SOCKDIR=`mktemp -d "${TMPDIR:-/tmp}"/epics.XXXXXXXXXXXX`

if [ $? -ne 0 ]; then
    echo "Error setting up for authentication"
    exit 1
fi
#echo "SOCKDIR=$SOCKDIR"
SOCK="$SOCKDIR/epics"

# Start a control master, then back ground it after it authenticates
ssh -M -S "$SOCK" -f -N -o "ControlPersist=yes" -l $USERNAME $GATEWAY || exit 1
echo
echo "Connection to $GATEWAY established"
echo "Searching for a free port to use for EPICS CA transport"
echo "The script will randomly select some ports in an attempt to find"
echo "an available network port to send the EPICS data over."

TRIES=1
FORWARD=0
PORT=0
# Try to find a port until we have created a FORWARD
while [ $FORWARD -eq 0 ]; do
    while [ $PORT -lt 5000 ] || [ $PORT -gt 65000 ]; do
        PORT=$RANDOM
    done
    
    echo "Attempting to use port $PORT for EPICS"
    echo "Forward attempt $TRIES"

    # this actually sets up the forwards and then goes away
    ssh -N -S "$SOCK" -o "ExitOnForwardFailure=yes" -L 127.0.0.1:$PORT:192.168.25.2:5064 -l $USERNAME $GATEWAY

    if [ $? -eq 255 ]; then
        # failure, try a different port
        PORT=0

        TRIES=$((TRIES+1))
        if [ $TRIES -gt 3 ]; then
            echo "Unable to find a free port to use in EPICS transport, aborting."
            echo "This is not a perminant error, please try running the script again."
            exit 1
        fi
    else
        # success
        FORWARD=1
    fi
done

EPICS_CA_AUTO_ADDR_LIST=NO
EPICS_CA_ADDR_LIST=
EPICS_CA_NAME_SERVERS=localhost:$PORT
EPICS_REMOTE_PATH=https://$GATEWAY/

LIGO_EPICS_REMOTE_CONNECTION=$SITE

export EPICS_CA_AUTO_ADDR_LIST EPICS_CA_ADDR_LIST EPICS_CA_NAME_SERVERS EPICS_REMOTE_PATH SITE site IFO ifo LIGO_EPICS_REMOTE_CONNECTION

echo

if [ -z "$*" ]; then
    PS1="remote epics $SITE\$ "
    export PS1
    echo "Launching bash shell setup to access EPICS at $SITE."
    echo "Use the 'exit' command to return to your regular environment."
    echo
	/bin/bash
else
    echo "Connected to EPICS at $SITE"
    echo "------------------"
    echo 
	$@
fi
