set -e

usage() {
echo "
   Purpose: Initialize CMTS LCLS2 test stand LLRF rack

   Usage: lcls2_rack.sh [-h] [-r rack] [-w datadir] [-p] [-q qf2predir]
                        [-s scriptdir] [-g pythonsetupfile] [-e pvprefix]
   Options:

   -h (optional) Print help

   -p (optional) Flag to program Kintex bitfiles before executing checkout.
                 (No value needed)

   -b (required if -p set) Bitfile name (with path)

   -r (optional) Rack ID. Options:
                A or a: rack A of LCLS-II cryomodule
                B or b: rack B of LCLS-II cryomodule

   -w (optional) Directory files are written to.

   -q (optional) Directory of qf2pre scripts.
                 If not specified, SLAC B15 directory is assumed

   -s (optional) Define path to RF scripts (lcls2_rack.sh, etc.)
       If not specified, current directory is assumed
       example for LERF: /usr/local/lcls/package/lcls2_llrf/software/prc

   -o (optional) EPICS PV prefix to write status to

   -k (optional) Flag to use Kintex fiber interface (used by LCLS systems)

   Examples:


   Test B15 Room 121 rack A and program bitfiles:
     lcls2_rack.sh -r a -p -w /data/cpu-b15-rf01 -k


   Exit code values:

         0   Rack checkout complete and successful
         1   Did not perform rack checkout
               (missing argument, etc.)
         2   Rack checkout failed

"
}

status() {
    SPC="############################################################"

    if [ "$STATUSPV" != "" ]; then
        if [ ! -x "$(command -v caput)" ]; then
            echo "Cannot execute caput. Skipping caput commands for the remainder."
            STATUSPV=""
        else
            CAPUT=$(caput -t $STATUSPV $1 2>&1)
            if [ $? -ne 0 ]; then
                printf "\\n\\tERROR: %s\\n\\n" "$CAPUT"
            fi
        fi
    fi

    printf "\\n\\n%s\\n %s\\n%s\\n" $SPC "$1" $SPC
}

program_bitfiles() {
    for R in $ALL; do
        status "programming kintex 7 for $R using $BITFILE"
        $PYTHON qf2_wrap.py -t $R program_kintex_7 -b $BITFILE -v
        status "finished programming $R"
    done
    cd $CURRENT
    status "FPGA programming complete"
}

board_information() {
    for R in $ALL; do
        status "Get board information for $R"
        $PYTHON qf2_wrap.py -t $R get_board_information
        status "Get Digitizer/ZEST serial number for $R"
        $PYTHON qf2_wrap.py -t $R read_fmc_prom -a 0 --device AT24C32D --length 27
    done
}

program_oscillators() {
    for R in $ALL; do
        status "Configure QF2 oscillators $R with frequency 1300/7 MHz"
        $PYTHON qf2_wrap.py -t $R program_oscillators -f 185.715 -o
    done
    status "Configuration of QF2 oscillators complete"
}

qsfp_check() {
    status "Checking QSFP mapping and status for $ALL"
    P="`pwd`"
    echo $CURRENT
    cd $SCRIPTPATH
    $PYTHON -u qsfp_chk.py --prc $PRCMGT --rfs1 $RFS1MGT --rfs2 $RFS2MGT
    cd $P
}

kintex_fiber_interfaces() {
    status "Program Kintex Fiber interfaces"
sleep 10
    # Enable and test Fiber Ethernet link
    $PYTHON lcls2_kintex_fiber_rack.py -r $RACK -x 1
sleep 30
    ping -c4 $RFS1
    ping -c4 $RFS2
    ping -c4 $PRC
    status "finished configuring Kintex fiber interfaces"
}

# Default to use rack A and not override write file location
echo ""
echo "Entering lcls2_rack_cmts.sh"
RACK="A"
DATADIR=""
DIRFLAG=""
PROGRAM=0
SPARTANFLAG=""
PYTHONPATH=""
SCRIPTPATH=""
STATUSPV=""
STATUSFLAG=""
BITFILE=""
USEKINTEX=0
USEEPICS=0
PYTHON=${PYTHON:-python3}

echo $PYTHON

# Command-line argument to define
# reference oscillator frequency [MHz]
# used by lcls2_rack_helper.py
# Set to " -f 50.0 " for Kintex copper Ethernet
# Set to " -f 125.0 " for Kintex fiber Ethernet
# If not defined, will use default (50 as of 9/27/21)
REFFLAG=""

# Define path to QF2 software
QF2_PATH="../submodules/qf2_pre"

while [ $# -gt 0 ];
do
    opt=$1;
    case $opt in
	"-h" )
	    usage
	    exit 1
	    ;;
	"-r" )
	    shift;
	    RACK=$(echo $1 | tr '[:lower:]' '[:upper:]')
	    rack=$(echo $RACK | tr '[:upper:]' '[:lower:]')
	    echo "Rack $RACK $rack"
	    shift
	    ;;
	"-w" )
	    shift;
	    DATADIR=$1
	    DIRFLAG="-w $DATADIR"
	    echo "Will write files to $DATADIR"
	    shift;
	    ;;
	"-p" )
	    shift;
	    PROGRAM=1
	    echo "Will load new bitfiles to FPGAs"
	    ;;
	"-s" )
	    shift;
	    SCRIPTPATH=$1
	    echo "Will execute scripts from $SCRIPTPATH"
	    shift;
	    ;;
	"-o" )
	    shift;
	    PVPREFIX=$1
	    USEEPICS=1
	    echo "Will use PV prefix ${PVPREFIX} for EPICS status updates"
	    STATUSPV=$PVPREFIX:TESTMSG
	    STATUSFLAG="-o $STATUSPV"
	    echo "Will write status to ${STATUSPV}"
	    shift;
	    ;;
	"-b" )
	    shift;
	    BITFILE=$1
	    echo "Will load bitfile ${BITFILE}"
	    shift;
	    ;;
	"-k" )
	    shift;
	    USEKINTEX=1
	    echo "Will use Kintex fiber interfaces"
	    ;;
	* )
	    echo "$opt not understood"
	    usage
	    exit 1
	    ;;
    esac
done
echo "Done parsing command-line options"

if [ "$RACK" = "A" ] || [ "$RACK" = "B" ]; then
    if [ $USEKINTEX = 1 ]; then
        RFS1=rfs1$rack
        RFS2=rfs2$rack
        PRC=prc$rack
        RFS1MGT=rfs1$rack-mgt
        RFS2MGT=rfs2$rack-mgt
        PRCMGT=prc$rack-mgt
        REFFLAG=" -f 125. "
    else
        RFS1=rfs1$rack
        RFS2=rfs2$rack
        PRC=prc$rack
        RFS1MGT=$RFS1
        RFS2MGT=$RFS2
        PRCMGT=$PRC
        REFFLAG=" -f 50. "
    fi
    RFS="$RFS1 $RFS2"
    echo ""
    echo "Rack $RACK: kintex $RFS1 $RFS2 $PRC, management $RFS1MGT $RFS2MGT $PRCMGT"
    echo ""
else
    echo "Illegal rack selection $RACK. Must be a, A, b, B. Aborting."	
    exit 1
fi

if [ "$SCRIPTPATH" != "" ]
then	
    cd $SCRIPTPATH
fi

status "Beginning checkout for rack $RACK"

if [ $PROGRAM = 1 ]; then
    CURRENT=$(pwd)
    cd ../submodules/qf2_pre

    ALL="$PRCMGT $RFS1MGT $RFS2MGT"
    board_information
    program_oscillators
    qsfp_check
    program_bitfiles

    if [ $USEKINTEX = 1 ]; then
        kintex_fiber_interfaces
    fi
fi

SCRIPT="lcls2_rack_helper.py"

status "Beginning $SCRIPT for Rack $RACK"

CMD="$PYTHON $SCRIPT -rfs1 $RFS1:803 -rfs2 $RFS2:803 -prc $PRC:803 -r $REFFLAG $SPARTANFLAG $DIRFLAG $STATUSFLAG"
echo "Running $CMD"
$CMD

status "Rack checkout complete"
exit 0
