#!/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 launches medm configured to access the $SITE read-only EPICS gateway."
    echo "By default it loads the system sitemap."
    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 "Any other options are passed directly to medm, please note you will need to specify an .adl file"
    echo
    echo "Special modes of operation:"
    echo "$0 sitemap - explicitly request the sitemap (default)"
    echo "$0 ODC - show the ODC summary screen SYS_CUST_ODC_MASTER_WORD.adl"
    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"
    exit $RETVAL
}

GATEWAY=lhoepics.ligo-wa.caltech.edu

IFO="H1"
SITE="lho"

USERAPPS="/opt/rtcds/userapps/release"
SITEMAP="/ligo/cds/$SITE/medm/sitemap.adl"
ODC="$USERAPPS/sys/common/medm/SYS_CUST_ODC_MASTER_WORD.adl"

SOCKDIR=
SOCK=
RETVAL=1

USERNAME=$USER

trap cleanup 0

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"

if [ "$LIGO_EPICS_REMOTE_CONNECTION" != "LHO" ]; then

    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 "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://lhoepics.ligo-wa.caltech.edu/

    export EPICS_CA_AUTO_ADDR_LIST EPICS_CA_ADDR_LIST EPICS_CA_NAME_SERVERS EPICS_REMOTE_PATH
else
    EPICS_REMOTE_PATH=https://lhoepics.ligo-wa.caltech.edu/
    export EPICS_REMOTE_PATH
fi

# from this point on we can connect to localhost:... and get EPICS CA from it

args="$SITEMAP"
macros="USERAPPS=$USERAPPS/"
if [ $# -eq 1 ]; then
    case  "$1" in
    sitemap)
        args="$SITEMAP"
    ;;
    ODC)
        args="$ODC"
        macros="IFO=$IFO,USERAPPS=$USERAPPS,ODCMASTER=MASTER"
    ;;
    *)
        args="$1"
    ;;
    esac
elif [ $# -gt 1 ]; then
        args=$@
fi

if [ "$macros" != "" ]; then
	macros="-macro $macros"
fi

medm $macros -x $args
RETVAL=0
