#!/bin/csh -f
#+
#OSIRIS library of scripts
#
#NAME
#     osirisConnect - powers on instrument, starts servers, and 
#                     checks out detectors.
#
#SYNOPSIS
#     osirisConnect
#
#DESCRIPTION
#     Prepares OSIRIS software for use after a move from the deck
#     to the AO room or vice versa.  Performs the following:
#       - Starts all servers and initializes them.  
#       - Starts logging
#       - Homes mechanisms (if ok to move)
#       - Locks mechanisms
#
#OPTIONS
#     -t #
#          ID number to attach to all script generated errors, warnings, and
#          questions that are passed to the OGS.  The ID number is separated
#          from the rest of the message with a ";".
#
#     -m
#          simulate calls to RPC servers.  during simulated calls, the 
#          command is echoed (instead of being executed).
#
#     others?
#
#EXAMPLES
#     script_name junk1 -t 123
#          What would happen?
#
#ENVIRONMENT VARIABLES
#     list of environment variables used
#
#FILES
#     list of files used
#
#SERVERS & KEYWORDS
#     list of the servers and keywords used, for example:
#
#     service = osiris
#          keywords: sfilter/ifilter, sscale
#
#SCRIPTS CALLED
#     list of the scripts called by this script, for example:
#
#     help, syncheck
#
#EXIT STATUS
#     0 - normal exit, no error
#     1 - script aborted by an interrupt
#     2 - syncheck error
#     3 - error parsing command line input
#     other errors...
#
#SEE ALSO
#     ???
#-
#
# Modification History:
# 20041124 - MB: Initial version created
# 20051129 - MB: Automatically use oprs backup gauge
# 20160531 - jlyke: Switch to oprs normal gauge, verify power before starting
#                   other servers
# 20180125 - jlyke: Back to oprs backup gauge, add osirisCheckoutDetector,
#                   add power for IMAG SAM (op1s pwstat4)
#

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

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

# Boilerplate for syncheck.
# Note that the boiler plate should be transparent for all usages,
# but to make correct use of syncheck you will need to specify the
# correct pattern.

set noglob
#set CheckStatus = `syncheck -command $0 $* -pattern text` 
set CheckStatus = 'OK'
unset noglob

if ("$CheckStatus" != "OK") then
    help $0 | more
    exit 2
endif

# End of help/syncheck boiler plate.

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

# Set default variable values
set unavail = ""

set oktoinitspec = 0  # flag for initializing detectors ok
set spectempnum = 1   # temp sensor number to check for detector init
set spectempmax = 80  # maximum temperature to allow detector init

set oktoinitimag = 0  # flag for initializing detectors ok
set imagtempnum = 2   # temp sensor number to check for detector init
set imagtempmax = 80  # maximum temperature to allow detector init

set oktomove = 0     # flag for mech moves ok
set mottempnum = 4   # temp sensor number to check for mech moves
set mottempmax = 80  # maximum temperature to allow mech moves

set waittime = 0
set maxwait = 5

set boottime = 60


# formulate lockeng password
set lockengpw = `date '+%y%m%d'`

# start the power servers and turn on power
set pwrprob = 0
#[436] osrseng@napili: showpower
#  
#****************************************************
# Power setting for Pulizzi 1 keyword server=op1s
#Stat    Keyword    Description 
#----    -------    -------------------------- 
# off => pwstat1   Unused 
# off => pwstat2   Unused 
# off => pwstat3   Unused 
# ON  => pwstat4   IMAG SAM
# ON  => pwstat5   Spec SAM 
# ON  => pwstat6   Imager PC
# ON  => pwstat7   Spec PC 
# ON  => pwstat8   EC Cooling System 
#               
# Power setting for Pulizzi 2 keyword server=op2s 
#Stat    Keyword    Description 
#----    -------    -------------------------- 
# ON  => pwstat1   Pressure Gauge 
# ON  => pwstat2   Lakeshore 340 
# ON  => pwstat3   Dewar Lakeshore 218 
# ON  => pwstat4   Cabinet Lakeshore 218 
# ON  => pwstat5   Motor Controllers 
# ON  => pwstat6   Terminal Server 
# off => pwstat7   Unused 
# ON  => pwstat8   EC Cooling System 
#****************************************************

foreach service ( op1s op2s )
    if (`osirisCheckServer ${service}` != 1) then
	# start server
	osiris start ${service}
	echo ""
    else
	echo "NOTICE: ${service} was already running"
	echo ""
    endif
    sleep 5

    set waittime = 0
    #check to see if alive.  if not, wait another a second and try again
    while ((`osirisCheckServer ${service}` != 1) && (${waittime} < ${maxwait}))
	sleep 1
	@ waittime ++
    end

    if (`osirisCheckServer ${service}` == 1) then
	echo "${service}:"
	modify -s ${service} lock=0
        modify -s ${service} init=1

	# put special server processing here
	switch (${service}) 
	    case op1s:
                set pwron = ( 4 5 6 7 8 )
                
                breaksw
	    case op2s:
                set pwron = ( 1 2 3 4 5 6 8 )
		breaksw
        endsw
        # turn on outlets if off
        foreach n ( $pwron )
          set pwr = `show -s ${service} -terse pwstat${n}`
          if ($pwr != 1 ) then
            modify -s ${service} pwstat${n}=1
            sleep 1
          else
            echo "NOTICE: pwstat${n} was already ON"
          endif
        end
        # verify power is on
        echo "Verify power status...sleeping 10 seconds"
        sleep 10 
        foreach n ( $pwron ) 
          set pwrstat = `show -s ${service} -terse pwstat${n}`
          if ( $pwrstat != 1 ) then
            @ pwrprob++
show -s ${service} pwstat${n}
          endif
        end
        # report and exit if something is not right
        if ( $pwrprob > 0 ) then
          echo "There is a problem with a power status"
          showpower
          exit 1
        endif
end

echo "Waiting for $boottime seconds for IMAG and SPEC PCs to boot"
sleep $boottime

# loop through each server and start it
foreach service (osds oids oprs ot1s ot2s otcs om1s om2s om3s om4s om5s om6s)
    if (`osirisCheckServer ${service}` != 1) then
	# start server
	osiris start ${service}
	sleep 5
	echo ""
    else
	echo "NOTICE: ${service} was already running"
	echo ""
    endif
end


# loop through each server
foreach service (oprs ot1s ot2s otcs om1s om2s om3s om4s om5s om6s osds oids)
    set waittime = 0
    #check to see if alive.  if not, wait another a second and try again
    while ((`osirisCheckServer ${service}` != 1) && (${waittime} < ${maxwait}))
	sleep 1
	@ waittime ++
    end

    if (`osirisCheckServer ${service}` == 1) then
	echo "${service}:"
	modify -s ${service} lock=0

	# put special server processing here
	switch (${service}) 
	    case op1s:
	    case op2s:
		# init
		modify -s ${service} init=1
		breaksw

	    case oprs:
		#automatically use the backup gauge
                set lockeng = `show -s ${service} -terse lockeng`
                if ($lockeng == 1 ) then 
		  modify -s ${service} lockeng=${lockengpw}
                endif
		modify -s ${service} backup=1
		modify -s ${service} lockeng=${lockengpw}

		# turn on logging
		modify -s ${service} logging=1
		modify -s ${service} pollhw=1
		breaksw

	   case ot1s:
		# turn on logging
		modify -s ${service} logging=1
		modify -s ${service} pollhw=1
	    	# get temp and determine if ok to move mechs
		set resp = `show -s ${service} -terse tmp${mottempnum}| cut -f1 -d.`
		if ("${resp}" < "${mottempmax}") then
		    set oktomove = 1
		endif
		breaksw

	   case ot2s:
		# turn on logging
		modify -s ${service} logging=1
		modify -s ${service} pollhw=1
		breaksw

	   case otcs:
		# turn on logging
		modify -s ${service} logging=1
		modify -s ${service} pollhw=1

		set resp = `show -s ${service} -terse tmp${spectempnum}| cut -f1 -d.`
		if ("${resp}" < "${spectempmax}") then
		    set oktoinitspec = 1
		endif

		set resp = `show -s ${service} -terse tmp${imagtempnum}| cut -f1 -d.`
		if ("${resp}" < "${imagtempmax}") then
		    set oktoinitimag = 1
		endif
		breaksw

	    case osds:
		if (${oktoinitspec} == 1) then
		    #modify -s ${service} init=1
                    osirisCheckoutDetector spec
		endif
		breaksw

	    case oids:
		if (${oktoinitimag} == 1) then
		    #modify -s ${service} init=1
                    osirisCheckoutDetector imag
		endif
		breaksw

	   case om1s:
	   case om2s:
	   case om3s:
	   case om4s:
	   case om5s:
	   case om6s:
		# home mechs if ok to move
		if (${oktomove}) then
		    modify -s ${service} home=1
		endif
		modify -s ${service} lock=1
		breaksw
	endsw

	#modify -s ${service} lockeng=1
	
    else
	echo "ERROR: ${service} is not running."
	set unavail = "${unavail}${service} "
    endif 

    echo ""

end

# start global server
osiris start ogs &

goto done

abort:
# Block of code to handle interrupts.
exit 1

done:
# is there anything that needs to go here?
exit