#!/bin/sh
# \
exec oagtclsh "$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)]

APSStandardSetup

set lastPing 0
#use the biggest non-used OAG runcontrol OAG199RC
set runControlPV DP:SRXrayBPMStatus
set pingTimeout 20
proc PingRunControl {args} {
    global runControlPV lastPing
    set sec [clock seconds]
    if {[expr $lastPing + 2] > $sec} {
        return
    } else {
        set lastPing $sec
    }

    catch {APSRunControlPing} status
    switch $status {
        RUNCONTROL_OK {}
        RUNCONTROL_ABORT {
            puts stderr "aborted."
            exit 1
        }
        RUNCONTROL_TIMEOUT -
        RUNCONTROL_ERROR {
            puts stderr "Unable to ping runcontrol record of $runControlPV: $status."
            exit 1
        }
    }
}

proc UpdateXrayBPMStatus {args} {
    eval after 1 UpdateXrayBPMStatus0 $args
}

proc UpdateXrayBPMStatus0 {args} {
    global varList sectorList P1X P2X P1Y P2Y xTextFile yTextFile
    eval global $varList
    set dataDir /home/helios/oagData/sr/orbitControllaw/lattices/default
    set tmpRoot /tmp/[APSTmpString]
    set fileList ""
    set plane ""
    APSParseArguments {plane}
    
    APSRunControlLogMessage -message "Updating $plane plane status" -severity 0
    switch $plane {
        x {
            set ext1 :OrbitCorrConfigX
            set ext2 :XrayBpmsInUseX
        }
        y {
            set ext1 :OrbitCorrConfigY
            set ext2 :XrayBpmsInUseY
        }
    }
    set Plane [string toupper $plane]
    if ![set ${plane}Running] {
        if [catch {exec cavput -list=ID -list=[join $sectorList ,] -list=$ext1=""
            exec cavput -list=ID -list=[join $sectorList ,] -list=$ext2=Disabled } result] {
            puts stderr "Error setting ID xbpm status2: $result"
        }
        if [catch {exec sddsmakedataset -col=Name,type=string -data=[join [concat [set P1${Plane}] [set P2${Plane}]] ,] \
                     -pipe=out \
                     | sddssort -pipe -col=Name \
                     | sddsprocess -pipe  "-print=col,ValueString,Not In Use" \
                     | sddsprintout -pipe=in [set ${plane}TextFile] -col=Name,format=%6s -col=ValueString,format=%10s \
                     -noTitle -noLabels } result] {
            puts stderr "Error in generating ${plane}TextFile: $result"
        }
    } else {
        set opt [APScagetTextFromWaveform -pvName DP:S:OrbitControlLaw${Plane}SDDS.OPTN]
        set config [file tail [file dir [lindex $opt 1]]]
        if [catch {APSMpSRSetXrayBPMStatusPVs -config $config} result] {
            return -code error "Error setting ID xbpm status1: $result"
        }
        set fileList ""
        foreach bpm {P1 P2} {
            set notUse ""
            set inUse ""
            if [catch {exec sddsprocess $dataDir/$config/config -match=par,NameType=MonitorNames \
                         -scan=col,Sector,Name,S%ld,type=long \
                         -match=col,Name=S*ID:$bpm -nowarnings $tmpRoot.${bpm}$plane  } result] {
                return -code error "Error getting inUse xbpms: $result"
            }
            set rows [exec sdds2stream -rows=bar $tmpRoot.${bpm}$plane]
            if !$rows {
                set notUse $sectors
            } else {
                set inUse [exec sdds2stream -col=Sector $tmpRoot.${bpm}$plane]
                if [catch {exec sddsselect /home/helios/oagData/sr/IDs/sectors.sdds $tmpRoot.${bpm}$plane -equate=Sector -invert -pipe=out \
                             | sdds2stream -pipe -col=Sector } notUse] {
                    return -code error "Error getting not used sectors: $notUse"
                }
            }
            if [llength $notUse] {
                if [catch {exec sddsmakedataset -col=Sector,type=long -data=[join $notUse ,] -pipe=out \
                             | sddsprocess -pipe=in $tmpRoot.$bpm.$plane.notuse \
                             -print=col,Name,%02d${bpm}:$Plane,Sector "-print=col,ValueString,Not In Use" } result] {
                    return -code error "Error1: $result"
                }
                lappend fileList $tmpRoot.$bpm.$plane.notuse
            }
            if [llength $inUse] {
                if [catch {exec sddsmakedataset -col=Sector,type=long -data=[join $inUse ,] -pipe=out \
                             | sddsprocess -pipe=in $tmpRoot.$bpm.$plane.inuse \
                             -print=col,Name,%02d${bpm}:$Plane,Sector "-print=col,ValueString,In Use" } result] {
                    return -code error "Error1: $result"
                }
                lappend fileList $tmpRoot.$bpm.$plane.inuse
            }
        }
        if [catch {eval exec sddscombine $fileList -merge -pipe=out \
                     | sddssort -col=Name -pipe \
                     | sddsprintout -pipe=in [set ${plane}TextFile] -noTitle -noLabels -col=Name,format=%6s -col=ValueString,format=%10s } result] {
            return -code error $result
        }
        eval file delete -force $fileList
    }
    APSRunControlLogMessage -message "Running" -severity 0
}


if [catch {APScavput -list=$runControlPV.CLR=1 -pend=20} result] {
    puts stderr "[exec date] error clear run control $runControlPV record: $result"
    exit
}
if [catch {APSRunControlInit -pv $runControlPV \
	       -description "SR Xray BPM status Server" \
	       -timeout [expr $pingTimeout * 1000] } result] {
    puts stderr "[exec date] Unable to initialize runcontrol DP:SRXrayBPMStatus, the runcontrol record may not be cleared, press the clear button on the medm screen to clear the record and restart: $result"
    exit
}
APSRunControlLogMessage -message "Running" -severity 0

set tmpFile /tmp/[APSTmpString]
if [catch {exec sddsprocess  /home/helios/oagData/sr/IDs/sectors.sdds -print=col,SectorStr,%02d,Sector -pipe=out \
             -print=col,P1X,%02dP1:X,Sector -print=col,P2X,%02dP2:X,Sector -print=col,P1Y,%02dP1:Y,Sector -print=col,P2Y,%02dP2:Y,Sector \
             | tee $tmpFile \
             | sdds2stream -pipe -col=SectorStr } sectorList] {
    puts stderr "Error getting ID sectors: $sectorList"
  #  exit 1
}
set sectors [exec sdds2stream -col=Sector /home/helios/oagData/sr/IDs/sectors.sdds]
APSAddToTmpFileList -ID 1 -fileList $tmpFile
foreach nm {P1X P2X P1Y P2Y} {
    set $nm [exec sdds2stream -col=$nm $tmpFile]
}

set pvList {DP:S:OrbitControlLawXSDDS.RUN DP:S:OrbitControlLawXSDDS.SUSP DP:S:OrbitControlLawYSDDS.RUN DP:S:OrbitControlLawYSDDS.SUSP}
set varList {xRunning xSusp yRunning ySusp}
if [pv linkw $varList $pvList 30] {
    puts stderr "Error link pvs: $errorCode"
    exit 1
}

set xTextFile /home/epics/OAG/Epics/inuseX.txt
set yTextFile /home/epics/OAG/Epics/inuseY.txt

PingRunControl

pv umon {xRunning xSusp} "UpdateXrayBPMStatus -plane x"
pv umon {yRunning ySusp} "UpdateXrayBPMStatus -plane y"
UpdateXrayBPMStatus -plane x
UpdateXrayBPMStatus -plane y

PingRunControl

while {1} {
    PingRunControl
    APSWaitWithUpdate -waitSeconds 5 -updateInterval 1 
}
exit
