#!/usr/bin/tclsh

foreach {adr obj} {
  IKA-GAMA:Luft_S10 luft
  IKA-GAMA:Luft_S2 luft_wlga
} {
  set values($adr) -1
  set objects($adr) $obj
}

proc readpipe {} {
  global sea values

  set line [gets $sea(pipe)]
  if {$sea(debug)} {
    puts stdout "> $line"
  }
  if {[eof $sea(pipe)]} {
   puts stdout EOF
   exit
  }
  lassign $line adr date time value
  set values($adr) $value
  send_to_sea
}

proc seacom {line} {
  global sea

  puts $sea(sock) $line
  flush $sea(sock)
  if {$sea(debug)} {
    puts stdout "> $line"
  }
}

proc send_to_sea {} {
  global sea values objects

  foreach adr [array names values] {
    if {$values($adr) >= 0} {
      seacom "$objects($adr) confirm $sea(heartbeat) $values($adr)"
    }
  }
  catch {after cancel $sea(afterid)}
  set sea(afterid) [after [expr int(1000 * $sea(heartbeat))] send_to_sea]
}

proc readsea {} {
  global sea values

  set line [gets $sea(sock)]
  if {[eof $sea(sock)]} {
    exit
  }
  if {$sea(debug)} {
    puts stdout "< $line"
  }
#  if {[scan $line {HEARTBEAT %d %s} sea(heartbeat) values($adr)]} {
#    send_to_sea
#  }
}

set env(EPICS_CA_ADDR_LIST) cryo-cagw:5062
set env(EPICS_CA_AUTO_ADDR_LIST) NO
set env(PATH) $env(PATH):/afs/psi.ch/project/sinq/rhel7/stow/base-3.15.5/bin/linux-x86_64-debug/

set sea(debug) [lindex "$argv 0" 0]
if {$sea(debug) eq "1"} {
  set sea(heartbeat) 20
} else {
  set sea(heartbeat) 300
  set sea(debug) 0
}

# connect to sea server prep0
set sea(sock) [socket samenv.psi.ch 8640]
fileevent $sea(sock) readable readsea
if {$sea(debug)} {
  seacom "seauser seaser"
} else {
  seacom "Spy 007"
}
set cmd "/afs/psi.ch/project/sinq/rhel7/stow/base-3.15.5/bin/linux-x86_64-debug/camonitor [array names values]"

set ret [catch {set proc [exec ps ax -o pid,args | grep $cmd]} msg]
set killed [list]
if {$ret == 0} {
  foreach line [split $proc "\n"] {
    set l [split [string trim $line]]
    set c [lrange $l 1 end]
    if {"$c" eq "$cmd"} {
      # process was still running
      lappend killed [lindex $l 0]
      exec kill -9 [lindex $l 0]
    }
  }
}

set sea(pipe) [open "|$cmd" r]
fileevent $sea(pipe) readable readpipe

set mypid [pid $sea(pipe)]
set f [open $env(HOME)/monitfiles/luft_camonitor.pid w]
puts $f $mypid
close $f

puts stdout $mypid
if {[llength $killed] > 0 && $sea(debug)} {
  puts stdout "killed $killed"
}

seacom "clientlog luft started"
vwait forever
