#!/bin/csh -f
#+
#OSIRIS library of scripts
#
#NAME
#     osirisCheckoutDetector - verifies OSIRIS detector is ready
#
#SYNOPSIS
#     osirisCheckoutDetector spec|imag
#
#DESCRIPTION
#     This script configures detector system software for taking
#     exposures.
#
#     All servers should be started before running this script.  The
#     script will report servers that were not configured since they were
#     not running.
#
#OPTIONS
#     password
#          the lockeng password - needed so that the script can unlock
#          servers to configure them
#
#EXAMPLES
#     osirisCheckoutDetector spec
#
#ENVIRONMENT VARIABLES
#     none
#
#FILES
#     none
#
#SERVERS & KEYWORDS
#     service = osds | oids
#          keywords: lockall, connect, connected, init, initing, framenum, 
#                    asiccfg, outdir, ready
#     service = otcs
#          keywords: curtmp1
#     service = op1s
#          keywords: lockall, pwstat4, pwstat5
#
#SCRIPTS CALLED
#     help, syncheck, osirisCheckServer, compareNumbers, osirisLockEngKeywords, osirisTakeExposure
#
#EXIT STATUS
#     0 - normal exit, no error
#     1 - script aborted by an interrupt
#     2 - syncheck error
#     3 - error parsing command line input
#     -1 - one or more servers not available
#     -2 - detector temperature above maximum allowed temperature
#     -3 - could not connect to SIDECAR Server
#     -4 - Initialization did not start on init command
#     -5 - Timeout waiting for initialization to complete
#     -6 - Detector system not ready after initialization
#
#SEE ALSO
#     ???
#-
#
# Modification History:
# 20110309  - JLW: Initial version created 
# 2016apr08 - MK : Updated with newdir command.
# 2016apr13 - jlyke: Adapted for OSIRIS SPEC
# 2018jan25 - jlyke: Generalized for OSIRIS IMAG
#

# Boiler plate for "-h" support for command autohelp.

if ("$1" == "-h") then
    help $0 | more
    exit $status
endif

# Set up to trap interrupts (Ctrl-C, etc.)
onintr abort

# Set default variable values
set unavail = ""
set datestamp = `date "+%y%m%d"`
set lockengpw = $datestamp
set exitcode = 0

# Check safety
set maxDetTemp = 80
set connectsleep = 10
# 10 seconds sleep between connect checks
set maxConnectAttempts = 10
set readysleep = 5
# 5 second sleep between init checks
set maxReadyChecks = 10  

set required_servers = (otcs op1s)

# Get command line arguments
while ( $#argv != 0 )
  switch ($1)
    case s*:
      set detserv = osds
      set det = SPEC
      breaksw
    case i*:
      set detserv = oids
      set det = IMAG
      breaksw
  endsw
shift
end

set required_servers = ($required_servers $detserv)

# Status line
echo ""
echo "Checking out OSIRIS $det detector:"

# Check required servers are running
foreach server ($required_servers)
  if (`osirisCheckServer $server` != 1) then
    echo "$server is not running."
    set unavail = "${unavail}$server "
  endif
end

if ("${unavail}" != "") then
    echo "WARNING:"
    echo "The following servers were not running:"
    echo "-> "${unavail}
    echo "exiting..."
    set exitcode=-1
    goto done
endif


echo Checking if detector temperature is below $maxDetTemp K
# get current detector temperature
set dettemp = `show -s otcs -terse tmp1 | cut -f 1 -d"."`
echo Current detector temperature is $dettemp K
if ($dettemp > $maxDetTemp || $dettemp <= 0) then
    echo "Detector temperature is outside nominal range"
    echo "exiting..."
    set exitcode=-2
    goto done
endif

# comment out since asicpwr is off before first init...
#echo "Checking power to $det SAM"
#set sam = `show -s $detserv -terse asicpwr`
#if ($sam == 0 ) then
  # SAM is powered off
#  echo "The $det SAM is powered off...exiting"
#  exit 1
#endif

echo "Confirming connection to $det SIDECAR Server"
set connected = `show -s $detserv -terse connected`
echo "Connected = $connected"

set connectAttempts=1
while ($connected != 1) 
    if ($connectAttempts > $maxConnectAttempts) then
	echo "Maximum SIDECAR Server connection attempts (${maxConnectAttempts}) exceeded.  Aborting..."
	set exitcode=-3
	goto done
    endif
    echo Detector server is not connected to $det SIDECAR Server.
    echo Waiting $connectsleep seconds before trying again
    sleep $connectsleep
    echo "Connect attempt $connectAttempts of $maxConnectAttempts"
    modify -s $detserv connect=1
    sleep 2
    set connected = `show -s $detserv -terse connected`
    echo "Connected = $connected"

    @ connectAttempts++
end

# if detector is exposing, it will not be ready.
echo "Checking whether a $det exposure is in progress"
set exposing = `show -s $detserv -terse exposing`
echo "Exposing = $exposing"
if ( $exposing == 1 ) then
  echo "$det Exposure in progress...exiting"
  exit 1
endif

# resume is a "softer" init than "init".  Try this first
echo "Determine whether $det detector is ready"
set ready = `show -s $detserv -terse ready`
if ( $ready != 1 ) then
  echo "Ready = $ready"
  echo "$det not ready, trying resume" 
  modify -s $detserv resume=1
  sleep 1
endif


set ready = `show -s $detserv -terse ready`
echo "Resume did not get the detector ready, trying init"
set readyChecks = 1
while ( $ready != 1 )
  if ( $readyChecks > $maxReadyChecks ) then
    echo "Max detector ready checks (${maxReadyChecks}) exceeded.  Aborting..."
    set exitcode=-5
    goto done
  endif
  set initcheck = `show -s $detserv -terse initing`
  if ( $initcheck == 0 ) then
    echo Initializing detector hardware
    modify -s $detserv init=1
  endif
  sleep $readysleep
  set ready = `show -s $detserv -terse ready`
  @ readyChecks++

end
echo "Ready = $ready"

echo "OSIRIS $det Checkout detector script successful."

goto done

abort:
# Block of code to handle interrupts.
set exitcode=1

done:

exit $exitcode
