#! /usr/bin/tclsh
package require Tk
global env
set HOME $env(HOME)
set NODE [info hostname]
set PROCDIR $HOME/Process_List_$NODE
wm title . "Process Control for Node $NODE"
#
#--->  Error pop up window.
proc pop_error {message} {
    toplevel .poper
    wm title .poper "Error"
    label .poper.err  -text "Error:"
    label .poper.text -text "$message"
    pack  .poper.err .poper.text -in .poper
    button .poper.ok  -text "OK" -command {
        focus .
        destroy .poper}
    pack   .poper.ok -in .poper
}
#
#    Format the control window.
#
frame .buts
button .quit   -text "Quit"    -command exit
button .nudg   -text "Nudge"   -command {
    set inx [.lbox curselection]
    if { "$inx" == "" } then {
	pop_error "No process selected"
    } else {
	foreach line $inx {
	    set proc [.lbox get $line]
	    set pidlink $PROCDIR/$proc/pid
	    if {[file type "$pidlink"] == "link" } then {
		set pid [file readlink $pidlink]
		if {"$pid" != "NA"} then {
		    exec kill -USR1 $pid
		} else {
		    pop_error "Process $proc not active"
		}
	    } else {
		pop_error "No process $proc"
	    }
	}
    }
}
button .kill   -text "Restart" -command {
    set inx [.lbox curselection]
    if { "$inx" == "" } then {
	pop_error "No process selected"
    } else {
	foreach line $inx {
	    set proc [.lbox get $line]
	    set pdir $PROCDIR/$proc
	    if {[file type "$pdir/pid"] == "link" } then {
		set pid [file readlink "$pdir/pid"]
		if {"$pid" != "NA"} then {
		    exec kill -TERM $pid
		} elseif {[file exists "$pdir/disable"] } then {
		    pop_error "Process $proc is disabled"
		} else {
		    if {[file readlink "$pdir/restarts"] == 0} then {
			file delete "$pdir/restarts"
			exec ln -s 5 $pdir/restarts
		    }
		    exec kill -HUP [file readlink "$pdir/mgrpid"]
		}
	    } else {
		pop_error "No process $proc"
	    }
	}
    }
}
button .disabl -text "Disable" -command {
    set inx [.lbox curselection]
    if { "$inx" == "" } then {
	pop_error "No process selected"
    } else {
	foreach line $inx {
	    set proc [.lbox get $line]
	    set pdir $PROCDIR/$proc
	    if {[file isdirectory "$pdir"] } then {
		exec touch $pdir/disable
	    } else {
		pop_error "No process $proc"
	    }
	}
    }
}
pack .quit .nudg .kill .disabl -in .buts -side left
#
set files [glob $PROCDIR/*]
listbox .lbox 
foreach f $files {
    .lbox insert end [file tail $f]
}
pack .lbox .buts

