#!/bin/bash
#==============================================================
# luSectorFromEpics
#
# Facility:  SLAC/LCLS
#
# Performs most of the functions associated with switching
# a Linac sector's CAMAC from EPICS/IOC control to SCP/Micro control
#
# Usage: luSectorFromEpics <location>
#
# Arguments: 
#            location: ioc location name, for example li28
# 
#----------------------------------------------------------------------------
# Mod:
#        
#==============================================================

loca=`echo $1 | tr '[:upper:]' '[:lower:]'`

LOCA=`echo $1 | tr '[:lower:]' '[:upper:]'`

# Start message

caput IOC:${LOCA}:CV01:QC_MSG "Begin ${LOCA} switch to SCP control..."

echo  Setting ${LOCA} to SCP control...
echo

# Set AIDA Klystron service to SLC

caput IOC:${LOCA}:CV01:QC_MSG "Set ${LOCA} AIDA Klys Service to SLC..."

echo  Switching ${LOCA} AIDA KLystron Service to SLC...

aidaqc_epicstoslc -a ${LOCA}

# Reconfigure and restart CAMAC CW process

caput IOC:${LOCA}:CV01:QC_MSG "Restarting CAMAC CW process..."

echo  Reconfiguring CAMAC Channel Watcher process...

luCWRestart ${LOCA} 0

# Rebooting CAMAC IOC with alternate Channel Access configuration...

caput IOC:${LOCA}:CV01:QC_MSG "Rebooting IOC-${LOCA}-CV01..."

luCamacIocAltPorts ${LOCA}

# Restarting Klystron Support soft ioc with SCP-mode databases...

caput IOC:${LOCA}:CV01:QC_MSG "Rebooting SIOC-${LOCA}-KY00..."

luKlystronSupportVmsMode ${LOCA}

# Update PV gateway cofiguration and restart gateway

caput IOC:${LOCA}:CV01:QC_MSG "Restarting PV gateway..."

caput SIOC:${LOCA}:1:CAMAC_CTRL 0

ssh laci@mcclogin ~mccuser/runluBuildGWConfig

$EPICS_IOC_TOP/QCT/scripts/gateway/restartGW.py

# Wait for IOC to boot before setting PSCD/MBCD PV

caput IOC:${LOCA}:CV01:QC_MSG "Pause 130 seconds (IOC booting)..."

echo "Pausing for 130 seconds (IOC booting)..."

sleep 130

# Set PSCD/MBCD PV

caput IOC:${LOCA}:CV01:QC_MSG "Set CAMAC control PV to SCP mode..."

echo  Setting MBCD Mode...

upgradeSetCamacControl ${LOCA} 1

# Restarting matlab klystron CUD process

caput IOC:${LOCA}:CV01:QC_MSG "Restarting Matlab Klys CUD process..."

ssh physics@lcls-srv03 Matlab_stop klystronCud

sleep 10

ssh physics@lcls-srv03 Matlab_startup klystronCud & 

sleep 5

# Restart MDL loop

caput IOC:${LOCA}:CV01:QC_MSG "Restarting MDL loop (takes 5 min)..."

echo  Restarting MDL loop, takes 5 minutes...

caput FBCK:MDL:1:STATUSDESC "Restarting MDL loop"

caput FBCK:MDL0:1:STATE 0

# Leave message up for 30 seconds so people see it but don't wait for restart to complete 
# before returning to switchover script. This is because people don't have to wait for the
# MDL loop restart to use the sector.

sleep 30 

luMDLRestart &

# Disable IOC alarms

echo Disabling IOC alarms...

caput IOC:${LOCA}:CV01:TODSUMFP 1
caput IOC:${LOCA}:CV01:HEARTBEATSUMFP 1

# End message

caput IOC:${LOCA}:CV01:QC_MSG "${LOCA} switch to SCP mode complete"

echo
echo

echo Switchover script complete

exit 0
