#!/bin/csh -f
#+
#OSIRIS library of scripts
#
#NAME
#     osirisFlushDetector - takes sufficient test frames to flush either
#          detector after doing an init or abort
#
#SYNOPSIS
#     osirisFlushDetector mode [-m]
#
#DESCRIPTION
#     takes a dark test frame with proper itime, numreads, and coadds to
#     flush either IMAG or SPEC detector after an abort or init.  after the
#     test frame is completed, the previous detector settings (itime, etc)
#     but the filter is left in Dark.
#
#OPTIONS
#     mode
#          specfies "SPEC" or "IMAG".
#
#     -m
#          simulate calls to RPC servers.  during simulated calls, the 
#          command is echoed (instead of being executed).
#
#EXAMPLES
#     osirisFlushDetector imag
#          flushes the imager detector
#
#ENVIRONMENT VARIABLES
#     none
#
#FILES
#     none
#
#SERVERS & KEYWORDS
#     service = osiris
#          keywords: scriptrun, ifilter, sfilter, itest, stest,
#
#     service = oids/osds
#          keywords: sampmode, calcreads, itime, coadds, getaokw, getdcskw,
#                    getkw, writeall
#
#SCRIPTS CALLED
#     help, syncheck, osirisScriptMsg, osirisCheckServer, wfmech, wfgo
#
#EXIT STATUS
#     0 - normal exit, no error
#     1 - script aborted by an interrupt
#     2 - syncheck error
#     3 - error parsing command line input
#     9 - required server not running
#     10 - dataset already active
#     11 - error setting filter keyword
#     12 - error getting detector keywords
#     13 - error setting detector keywords
#     14 - error starting exposure
#
#SEE ALSO
#     ???
#-
#
# Modifcation History:
# 20051007 - MB: Initial version created
# 20051119 - MB: removed usage of setstatus keyword
# 20051121 - MB: added init of detector at beginning if needed
#                forced resetting det kw to orig vals even if flush fails
# 20080304 - JLW: Updated filter list with new pupil filters
#

# 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.

### More advanced argument checking is required, see below

# End of help/syncheck boiler plate.

# Set up to trap control-C
onintr break

# Set default variable values
set fcmd = $0
set cmd = ${fcmd:t}
set cmdpre = ""
set cmdsuf = ""
set init_try_limit = 2
set flush_success = 0
set scriptrun_set = 0
set osiris_server_up = 0
set det_kw = (sampmode calcreads itime coadds getaokw getdcskw getkw writeall)
set old_det_kw_vals = ""
set det_kw_changed = 0

# Decide if we should use SPEC or IMAG
set mode = $1
switch ($mode)
    case "SPEC":
    case "spec":
	set M = "s"
	set mode = "spec"
	set filtlist = "[Jbb,Hbb,Kbb,Zbb,Kcb,Jn1,Jn2,Jn3,Jn4,Hn1,Hn2,Hn3,Hn4,\
			  Hn5,Kn1,Kn2,Kn3,Kn4,Kn5,Zn4,Kc3,Kc4,Kc5,Drk]"
	# look at the det_kw variable above to see what the list values mean
	set flush_det_kw_vals = (1 1 2 10 0 0 0 0)
	breaksw
    case "IMAG":
    case "imag":
	set M = "i"
	set mode = "imag"
	set filtlist = "[Opn,Jbb,Hbb,Kbb,Zbb,Jn1,Jn2,Jn3,Hn1,Hn2,Hn3,Hn4,Hn5,\
			  Kn1,Kn2,Kn3,Kn4,Kn5,Zn3,Drk]"
	# look at the det_kw variable above to see what the list values mean
	set flush_det_kw_vals = (1 1 2 10 0 0 0 0)
	breaksw
    default:
	osirisScriptMsg -T $cmdsuf "${cmd}: Specified mode must be SPEC or"\
	    "IMAG - aborting."
	osirisScriptMsg -T $cmdsuf "${cmd}: Usage: ${cmd} mode [-m]"
	set exitcode = 3
	goto done
	breaksw
endsw
shift

# Check for more flags
set noglob
while ($#argv != 0)
    switch ($1)
	case -m:
	    set sim
	    set cmdpre = "echo ${cmd} ${mode}: sim:"
	    set cmdsuf = "-m"
	    breaksw
	default:
	    osirisScriptMsg -T $cmdsuf "${cmd}: Invalid command line flag"\
		"${1} specified."
	    osirisScriptMsg -T $cmdsuf "${cmd}: Usage: ${cmd} mode [-m]"
	    # set the error code for an error with command line input
	    set exitcode = 3
	    goto done
	    breaksw
    endsw
    shift
end
unset noglob

###should do something if there are no arguments...
###currently, script does nothing and exits successfully

# Check if global and detector server are running, and if a dataset is running
if ($?sim) then
    set dataset_active = 0
else
    # Check the global server
    set osiris_server_up = `osirisCheckServer osiris`
    if ($osiris_server_up) then
	# Check if another script is running
	set scriptrun = `show -s osiris -terse scriptrun`
	if ($scriptrun) then
	    osirisScriptMsg -T $cmdsuf "${cmd}: Another script appears to be"\
		"running (scriptrun = 1)."
	    set exitcode = 10
	    goto done
	endif
    else
	osirisScriptMsg -T $cmdsuf "${cmd}: Global server is not running."
	set exitcode = 9
	goto done
    endif

    # Check the detector server
    set detector_server_up = `osirisCheckServer o${M}ds`
    if ($detector_server_up != 1) then
	osirisScriptMsg -T $cmdsuf "${cmd}: o${M}ds server is not running."
	set exitcode = 9
	goto done
    endif
endif

# Alert others that a script is running
$cmdpre modify -s osiris silent scriptrun=1
set scriptrun_set = 1

# Initialize the detector and make sure it was successful
set init_tries = 0
while ($init_tries <= $init_try_limit)
    # Initialize the detector
    $cmdpre modify -s o${M}ds silent init=1
    set error = $status
    if ($error != 0) then
	osirisScriptMsg -T $cmdsuf "${cmd}: Error initializing ${mode}"\
	    "detector (modify error #${error})."
	set exitcode = 13
	goto done
    endif
    @ init_tries++

    # Check that init was successful
    set temp_val = `show -s o${M}ds -terse status`
    set error = $status
    if ($error != 0) then
	# Check the detector server again, necessary since if the detector
	# was in a wierd state to begin with, the init may have killed it
	set detector_server_up = `osirisCheckServer o${M}ds`
	if ($detector_server_up != 1) then
	    osirisScriptMsg -T $cmdsuf "${cmd}: o${M}ds server is not running."
	    set exitcode = 9
	    goto done
	endif

	# If detector server is running, but we were unable to get the status,
	# then something strange is happening - we should give up now
	osirisScriptMsg -T $cmdsuf "${cmd}: o${M}ds server appears to be up,"\
	    "but unable to get status keyword.  Please investigate health"\
	    "of o${M}ds server."
	set exitcode = 12
	goto done
    else
	# Make sure the detector is happily idling
	if ("${temp_val}" == "Idling") then
	    # Everything looks good, exit the while loop
	    @ init_tries = $init_try_limit + 1
	else
	    # If we reached the init_try_limit, something is up with the
	    # detector server - we should give up now, otherwise try again
	    if ($init_tries >= $init_try_limit) then
		osirisScriptMsg -T $cmdsuf "${cmd}: ${mode} detector inits"\
		    "are not working, even though o${M}ds server appears to"\
		    "be up.  Please investigate health of o${M}ds server."
		set exitcode = 13
		goto done
	    else
		# Try another init by letting while loop repeat
	    endif
	endif
    endif
end

# Set filter to dark
$cmdpre modify -s osiris silent ${M}filter=Drk
set error = $status
if ($error != 0) then
    osirisScriptMsg -T $cmdsuf "${cmd}: Error setting {$M}filter to Drk"\
		       "(modify error #${error})."
    set exitcode = 11
    goto done
endif

# Get the current detector settings
if ($?sim) then
    # look at the det_kw variable above to see what the list values mean
    set old_det_kw_vals = (1 1 2 1 1 1 1 0)
else
    foreach k (${det_kw})
	set val = `show -s o${M}ds -terse ${k}`
	set error = $status
	if ($error != 0) then
	    osirisScriptMsg -T $cmdsuf "${cmd}: Error getting detector"\
		"keyword <${k}> (show error #${error})."
	    set exitcode = 12
	    goto done
	endif
	set old_det_kw_vals = (${old_det_kw_vals} ${val})
    end
endif

# Set the detector keywords for the flush
set i = 0
set det_kw_changed = 1
foreach k (${det_kw})
    @ i++
    $cmdpre modify -s o${M}ds silent ${k}=${flush_det_kw_vals[$i]}
    set error = $status
    if ($error != 0) then
	osirisScriptMsg -T $cmdsuf "${cmd}: Error setting detector keyword"\
	    "<${k}> (modify error #${error})."
	set exitcode = 13
	goto done
    endif
end

# Make sure nothing is moving
$cmdpre wfmech $mode

# Actually take the flush frame
$cmdpre modify -s osiris silent ${M}test=1
set error = $status
if ($error != 0) then
    osirisScriptMsg -T $cmdsuf "${cmd}: Error starting test frame"\
	"(modify error #${error})."
    set exitcode = 14
    goto done
endif
set flush_success = 1

# Wait for the frame to finish
$cmdpre wfgo ${mode}

# Jump to the done block
goto done



break:
# Block of code to handle interrupts.

# Alert the user
osirisScriptMsg -T $cmdsuf "${cmd}: User abort received."

# Set a non-zero exit code and exit
if ($?exitcode) then
    set exitcode = -1
endif

# Finish with the normal script clean-up
goto done



done:
# Block of code to execute regardless of what happened

# Set the keywords back to what they were before the flush
if ($det_kw_changed) then
    set i = 0
    foreach k (${det_kw})
	@ i++
	$cmdpre modify -s o${M}ds silent ${k}=${old_det_kw_vals[$i]}
	set error = $status
	if ($error != 0) then
	    osirisScriptMsg -T $cmdsuf "${cmd}: Error reverting detector"\
		"keyword <${k}> (modify error #${error})."
	    # if no error code already, set one now
	    if ($?exitcode) then
		set exitcode = 13
	    endif
	endif
    end
endif

# Alert the user
if ($flush_success) then
    osirisScriptMsg -T $cmdsuf "${cmd}: ${mode} detector was flushed."
else
    osirisScriptMsg -T $cmdsuf "${cmd}: ${mode} detector was NOT flushed."
endif

# Notify that this script is done
if ($osiris_server_up && $scriptrun_set) then
    $cmdpre modify -s osiris silent scriptrun=0
    set error = $status
    if ($error != 0) then
	osirisScriptMsg -T $cmdsuf "${cmd}: Error setting OGS keyword"\
	    "scriptrun=0 (modify error #${error})."
	# if no error code already, set one now
	if ($?exitcode) then
	    set exitcode = 13
	endif
    endif
endif

# Exit with the proper exit code
if ($?exitcode) then
    exit $exitcode
else
    exit
endif
