#!/bin/sh  
# \
exec oagwish "$0" "$@"

set auto_path [linsert $auto_path 0  /usr/local/oag/apps/lib/$env(HOST_ARCH)]
set auto_path [linsert $auto_path 0 /usr/local/oag/lib_patch/$env(HOST_ARCH)]
set apsttk 1
APSDebugPath

proc SetMainStatus {text} {
    global mainStatus
    set mainStatus $text
    update
}

set w0 .userFrame


set rcPV S-INJ:TopLevelInjPermissiveC
set checkSumRCPV S-INJ:TopLevelInjCheckSumsC

set wantRunning 0

proc StartPermissive {} {
    global w0 rcPV wantRunning
    SetMainStatus "Starting"
    set input /home/helios/oagData/sr/permissive/sr-permissive.sdds
    APSExecLog .pexec -parent $w0.runFrame.frame -name PermissiveExec -width 120 -okButton 0 -cancelButton 0 -abortButton 0 \
        -unixCommand "sddspermissive $input -runControlPV=string=$rcPV,pingTimeout=10,pingInterval=1 -verbose"
    set wantRunning 1
    after 10000 CheckIfRestartNeeded
}

proc AbortPermissive {} {
    global rcPV wantRunning
    SetMainStatus "Aborting"
    if [catch {exec cavput -list=$rcPV.ABRT=1} result] {
        SetMainStatus "$result"
    }
    set wantRunning 0
}

proc CheckIfRestartNeeded {} {
    global w0 wantRunning rcPV
    if {$wantRunning} {
        set lastLine [lindex [split [$w0.runFrame.frame.pexec.userFrame.text.text index end] .] 0]
        set prev5Lines [expr $lastLine - 5]
        if {$prev5Lines < 1} {
            set prev5Lines 1
        }
        set lastLine [lindex [split [string trim [$w0.runFrame.frame.pexec.userFrame.text.text get $prev5Lines.0 $lastLine.end]] \n] end]
        if {($lastLine == "Run control application aborted.")} {
            set wantRunning 0
            return
        }
        if {($lastLine == "Run control application timed out.") ||
            ($lastLine == "Communications error with runcontrol record.") ||
            ($lastLine == "Unknown run control error code.")} {
            if {[catch {exec cavget -list=$rcPV.RUN -printError -pend=1} results]} {
            } else {
                StartPermissive
                return
            }
        }
        after 10000 CheckIfRestartNeeded
    }
}

proc CheckPermissive {} {
    set tmpRoot /tmp/[APSTmpString]
    SetMainStatus "Checking..."
    if [catch {exec sddssnapshot /home/helios/oagData/sr/permissive/sr-permissive.sdds $tmpRoot.snap -pendIoTime=15} result] {
        SetMainStatus "$result"
        return
    }
    if [catch {exec sddsprocess $tmpRoot.snap $tmpRoot.CAError -match=col,CAError=y -nowarning
        exec sddsprocess $tmpRoot.snap $tmpRoot.valueError "-test=column,Value MinimumValue < Value MaximumValue > ||"
        exec sddscombine $tmpRoot.CAError $tmpRoot.valueError -pipe=out -merge \
                 | sddsprintout -pipe=in $tmpRoot.txt "-title=Permissive check from [clock format [clock seconds]]" \
                 -column=ControlName,format=%24s -column=CAError -column=MinimumValue,format=%12.6f \
                 -column=Value,format=%12.6f -column=MaximumValue,format=%12.6f} result] {
        SetMainStatus "$result"
        return
    }
    APSFileDisplayWindow .wcheck -autoWidth 1 -autoWidthLimit 140 -fileName $tmpRoot.txt -deleteOnClose 1
}


APSApplication . -name swapOutPermissiveLauncher -version 1.0 \
  -overview "Provides interface to start, monitor, and stop the swap-out permissive."

set mainStatus Ready.
APSScrolledStatus .status -parent .userFrame -textVariable mainStatus -width 120 \
  -contextHelp "Provides a scrolling status display." -packOption "-fill x"

APSFrame .frame1 -parent $w0 -packOption "-side top" -relief flat
set w1 $w0.frame1.frame

APSFrame .buttonFrame1  -parent $w1 -packOption "-side left" -label "Permissive"
set w2 $w1.buttonFrame1.frame
APSButton .start -parent $w2 -text "START" -width "" -command "StartPermissive" -contextHelp "Press to start the permissive."
APSButton .info -parent $w2 -text "INFO" -width "" \
    -command "exec medm -x -attach -macro RCPV=$rcPV /C2/screens/adl/iocs/inj-orch/APSRunControlSingle.adl &" \
    -contextHelp "Press to launch MEDM window for the run control record."
APSButton .abort -parent $w2 -text "ABORT" -width "" -command "AbortPermissive" -contextHelp "Press to abort the permissive."
APSButton .check -parent $w2 -text "CHECK" -width "" -command "CheckPermissive" -contextHelp "Press to check the state of the readbacks monitored by the permissive."

APSFrame .buttonFrame2 -parent $w1 -packOption "-side right" -label "Checksum Validator"
set w2 $w1.buttonFrame2.frame
APSButton .info -parent $w2 -text "INFO" -width "" \
    -command "exec medm -x -attach -macro RCPV=$checkSumRCPV /C2/screens/adl/iocs/inj-orch/APSRunControlSingle.adl &" \
    -contextHelp "Press to launch MEDM window for the run control record."

APSFrame .runFrame -parent $w0 -width 120 -packOption "-side bottom"
