#!/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 args $argv
set debug 0
if {[APSStrictParseArguments {debug}]} {
    return -code error "usage: startSddspcas \[-debug 1\]"
}

cd /home/helios/oagData/sddspcas/[lindex [split $apsScriptHost .] 0]

if ![llength [set pcasFileList [lsort [glob -nocomplain *.pcas]]]] {
    exit 1
}

# Try to contact the PVs via channel access
set tmpRoot /tmp/[APSTmpString]
APSAddToTempFileList $tmpRoot.1

catch {eval exec sddscombine $pcasFileList -merge -pipe=out \
         | sddssnapshot -pipe -pend=5 \
         | sddsprocess -pipe=in  $tmpRoot.1 -match=column,CAError=n,! -nowarning} result
if $debug { puts stderr "CA attempt done: $result" }
if [catch {exec sdds2stream $tmpRoot.1 -rows=bare} rows] {
    if $debug { puts stderr "Problem with $tmpRoot.1---exiting" }
    exit 1
}
if $rows==0 {
    # all PVs ok, so exit.  Server is running
    if $debug { puts stderr "Server already running---exiting" }
    exit 0
}

if {[catch {exec ps -fe | fgrep sddspcas | fgrep daq-pv-group-pvs} pid]} {
    if {$pid == "child process exited abnormally"} {
        file copy -force /home/helios/iocinfo/oagData/pvdata/iocRecNames.sdds.backup /home/helios/iocinfo/oagData/pvdata/iocRecNames.sdds
    }
}

if ![file exists sddspcas.log] {
    set fd [open sddspcas.log w]
    puts $fd "[clock format [clock seconds]]"
    close $fd
}

if $debug { puts stderr "Attempting to start server" }
exec echo "[clock format [clock seconds]]: Attempting to start server" >>& sddspcas.log 
eval exec sddspcas -executionTime=0 -master=/home/helios/oagData/pvdata/iocRecNamesOAG.sdds $pcasFileList >>& sddspcas.log &
exit 0
