#!/usr/bin/env tclsh
#set svcPort 9999
set args [ic_argv]
set port ""
foreach {n v} $args {
    set $n $v
}

mess "serverport: $port\n" red

set svcPort $port
# Implement the service
# This example just writes the info back to the client...
proc doService {sock msg} {
	    # puts $sock "echosrv:$l"
	if [catch {eval $msg} res] {
		puts $sock "error in executing $msg"
		puts $sock "Job Failed"
		close $sock
	} else {
	     puts $sock $msg 
	     puts $sock "Job Complete"
	}
     }

# Handles the input from the client and  client shutdown
proc  svcHandler {sock} {
     set l [gets $sock]    ;# get the client packet
        if {[eof $sock]} {    ;# client gone or finished
            close $sock        ;# release the servers client channel
           } else {
	    doService $sock $l
           }
         }

proc read_stdout {wsock} {
  global  eventLoop
  set l [gets stdout]
  if {[eof stdout]} {
    #close $wsock             ;# close the socket client connection
    #set eventLoop "done"     ;# terminate the vwait (eventloop)
  } else {
    puts $wsock $l           ;# send the data to the server
  }
}

proc kill_proc {} {
set user_name [exec whoami]
exec ps -u $user_name >/tmp/pid_info
set proc_file /tmp/pid_info
set l 0
set proc_info_file [open $proc_file r]

while {[gets $proc_info_file ln] >=0} {
   incr l
   if {([regexp "med" $ln]) || ([regexp "tetra" $ln]) || \
      ([regexp "tri2tet" $ln]) || ([regexp "prism" $ln])} {
   set proc_id [lindex $ln 0]
   exec kill -9 $proc_id
  }
}
close $proc_info_file
}

# Accept-Connection handler for Server. 
# called When client makes a connection to the server
# Its passed the channel we're to communicate with the client on, 
# The address of the client and the port we're using
#
# Setup a handler for (incoming) communication on 
# the client channel - send connection Reply and log connection
proc accept {sock addr port} {
					        
# if {[badConnect $addr]} {
#     close $sock
#     return
# }

# Setup handler for future communication on client socket
fileevent $sock readable [list svcHandler $sock]
# fileevent stdout readable [list read_stdout $sock]
# Read client input in lines, disable blocking I/O
fconfigure $sock -buffering line -blocking 0

# Send Acceptance string to client
puts $sock "$addr:$port, You are connected to the server."
puts $sock "It is now [exec date]"
#set proc_info [catch {exec /tmp/medbatch_startup18.csh &} res] 
#puts $sock $res 
#puts $sock "The PID is [exec ps -elf | grep med]"
# log the connection
puts "Accepted connection from $addr at [exec date]"
}
# Create a server socket on port $svcPort. 
# Call proc accept when a client ATTempts a connection.
socket -server accept $svcPort
vwait events    ;# handle events till variable events is set
