#!/bin/bash
#==============================================================
#  Name: rfInitRes.sh
#  Abs:  Initialize resonance chassis for LCLS-II LLRF
#
#  Facility: LCLS-II
#============================================================

function usage {
echo "
   Purpose: This runs res_ctl.py, which programs the Kintex
            firmware and performs other initialization.

            Previous settings/values will be lost
   Usage:
       $0 <prefix> <ip> <bitfile> <scriptdir>

       Required:

          PREFIX:     Chassis PV prefix, ex ACCL:AD10:0100:RESA

          IP:         Chassis IP, ex 192.168.0.100

          BITFILE:    Kintex bitfile name, including path

          SCRIPTDIR: Full path to lcls2_llrf/software/res_ctl
"
}

# Check for input arguments
NARGS=$#
if [ $NARGS -ne 4 ]
then
        echo "$0: 4 arguments expected, but received ${NARGS}."
        usage
        exit 0
fi

PREFIX=`echo $1`
IP=`echo $2`
BITFILE=`echo $3`
SCRIPTDIR=`echo $4`

# Resolve relative path, if any
BITFILE=$(readlink --canonicalize $BITFILE)
SCRIPTDIR=$(readlink --canonicalize $SCRIPTDIR)

# Halt communication between EPICS and chassis
caput -t $PREFIX:CTRL_HALT 1

echo "Executing python ${SCRIPTDIR}/res_ctl.py -a $IP -r -b $BITFILE"
xvfb-run python ${SCRIPTDIR}/res_ctl.py -a $IP -r -b $BITFILE

# Resume communication
caput -t $PREFIX:CTRL_RESET 1

sleep 2

echo 'Done'

exit 0
