#!/bin/bash
#==============================================================
#  Name: rfLoadFwCmts.sh
#  Abs:  For LCLS-II CMTS LLRF chassis, load Kintex firmware
#
#  Facility: LCLS-II
#
#  Auth: Sonya Hoobler, 07 Jun 2023
#  Rev:  dd-mmm-yyyy, First Lastname (USERNAME)
#
#
#--------------------------------------------------------------
#  Mod:
#
#--------------------------------------------------------------
#
#  Usage:
#         rfLoadFwLcls2.sh <ip> <scriptdir> <bitfile>
#
#============================================================

function usage {
echo "
   Purpose: This programs the Kintex for the specific IP/chassis,
            resulting in many registers left at default values.
            Caller should halt, then resume EPICS communication
            if appropriate.

   Usage:

       rfLoadFwCmts.sh <prefix> <ip> <bitfile> <scriptdir>

       Required:

          PREFIX      Chassis PV prefix

          IP:         IP address

          SCRIPTDIR:  Path to lcls2_llrf/software/submodules/qf2_pre directory

          BITFILE:    Kintex bitfile name, including path

"
}

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

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

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

CURRENT=`pwd`
echo $CURRENT
cd $SCRIPTDIR
CMD="python qf2_wrap.py -t $IP program_kintex_7 -b $BITFILE"
echo "Executing this command: ${CMD}"
$CMD
cd $CURRENT

# Resume communication
caput -t $PREFIX:CTRL_RESET 1 

exit 0
