#!/bin/csh -f
#+
#OSIRIS library of scripts
#
#NAME
#     osirisStopGuis -- Stop the OSIRIS observing GUIs
#
#SYNOPSIS
#     osirisStopGuis [-t #] [-m] etc...
#
#DESCRIPTION
#     Called via a pulldown or from osirisEndNight to stop GUIs
#
#OPTIONS
#     -t #
#          ID number to attach to all script generated errors, warnings, and
#          questions that are passed to the OGS.  The ID number is separated
#          from the rest of the message with a ";".
#
#     -m
#          simulate calls to RPC servers.  during simulated calls, the 
#          command is echoed (instead of being executed).
#
#     others?
#
#EXAMPLES
#     osirisStopGuis
#
#ENVIRONMENT VARIABLES
#     list of environment variables used
#
#FILES
#     list of files used
#
#SERVERS & KEYWORDS
#     list of the servers and keywords used, for example:
#
#     service = osiris
#          keywords: sfilter/ifilter, sscale
#
#SCRIPTS CALLED
#     list of the scripts called by this script, for example:
#
#     help, syncheck
#
#EXIT STATUS
#     0 - normal exit, no error
#     1 - script aborted by an interrupt
#     2 - syncheck error
#     3 - error parsing command line input
#     other errors...
#
#SEE ALSO
#     ???
#-
#
# Modification History:
# 20041124 - MB:    Initial version created
# 20100517 - jlyke: Broken out from osirisSetupNight
# 20120202 - jlyke: Switched to svncserver1 
# 20200603 - jlyke: Changed method to stop IDL
#
#-----------------------------------------------------------------------------
# Boiler plate for "-h" support for command autohelp.

if ("$1" == "-h") then
    help $0 | more
    exit $status
endif

# Set up to trap interrupts (Ctrl-C, etc.)
onintr abort

# Set default variable values
set cmdpre = ""
set cmdsuf = ""
set idnum = 0

# Check for flags
set noglob
while ($#argv != 0)
##echo "${0} ${mode}: Checking ${1}..."
    switch ($1)
	case -t:
	    set CheckStatus = `syncheck -command $1 $2 -pattern int`
	    if ("$CheckStatus" == "OK") then
		set idnum = $2
		shift
	    else
		echo "${0} ${mode}: Invalid script ID number specified <${2}> - using ${idnum}."
	    endif
	    unset Checkstatus
	    breaksw
	case -m:
	    set sim
	    set cmdpre = "echo ${0}: sim:"
	    set cmdsuf = "-m"
	    breaksw
	default:
	    echo "${0}: Invalid command line flag $1 specified."
	    echo "${0}: Usage: $0 [-t #] [-m]"
	    # set the error code for an error with command line input
	    exit 3
	    breaksw
    endsw
    shift
end
unset noglob

#-----------------------------------------------------------------------------
# Define computers and accounts
set num = `inst2tel` 
set tel = `echo "k"$num`
set aoacct = `echo $tel"obsao"`
set aoserver = `echo $tel"aoserver"`
set lacct = `echo $tel"laser"`
set lserver = `echo $tel"laserserver"`
set sserver = osirisserver
set dserver = osirisdrp

# kxruts, kxserver, magiq, dcsx
set telacct = `echo $tel"ruts"`
set telserv = `echo $tel"server"`
set mserv = `echo $tel"-magiq-server"`
set dcs = `echo "dcs"$num`

# VNC
set vnccomp = `kvncinfo -server`
# convert vnc_comp to real computer name
set vnchost = `ypcat hosts | grep -w $vnccomp | sort -u | awk '{print $2}'`
set ports = `kvncstatus -q -u $USER`
#-----------------------------------------------------------------------------
# OSIRIS GUIs working in the general way
set glist = ( oopgui odec osgui otgui oorgui odrfgui idl)
foreach g ($glist)
  osiris stop $g
end
# Other GUIs running running on VNCserver
set olist = ( Facsum Met ObserverUI eventsounds )
foreach o ($olist)
  set pidlist = `ps -eo "user pid args" | grep $o | grep -v grep | grep ^$USER | awk '{print $2}'`
  echo "Killing $o, PID=$pidlist"
  kill -9 $pidlist
end
# No lsof on kN-magiq-server so shut them all down...
#xrsh -l $telacct $mserv magiq stop ObserverUI
# can start ObserverUI as any user so shutdown this users version
#ssh -X $mserv magiq stop ObserverUI
# kill the pig
#set pig_pid = `rsh kalahuipuaa /usr/ucb/ps -auxww | grep pig | grep -v grep | awk '/^'$USER'/ {print $2}'`
#echo "killing the PIG"
#rsh kalahuipuaa kill -9 $pig_pid
#-----------------------------------------------------------------------------
# Kill other tasks
echo "Killing other GUIs"
# Define a no-kill list of tasks, pid's will be searched
set tno_kill = ()
set ano_kill = ()
set lno_kill = ()
set sno_kill = ()
set dno_kill = ()
# on dserver (linux), these will be "idl", "xterm", "wait_wrap", etc.

# define empty no kill pid lists
set tno_pids = ()
set ano_pids = ()
set lno_pids = ()
set sno_pids = ()
set dno_pids = ()
#-----------------------------------------------------------------------------
# populate the no kill pid lists
# 2020-07-02 jlyke kNserver retirement, facsum, met run on vm-osiris
#foreach task ($tno_kill)
#  set ttask_pids = `rsh -l $telacct $telserv lsof | grep $task | awk '{print $2}' | sort -u`
#  set tno_pids = ($tno_pids $ttask_pids)
#end
foreach task ($ano_kill)
  set atask_pids = `rsh -l $aoacct $aoserver lsof | grep $task | awk '{print $2}' | sort -u`
  set ano_pids = ($ano_pids $atask_pids)
end
foreach task ($lno_kill)
  set ltask_pids = `rsh -l $lacct $lserver lsof | grep $task | awk '{print $2}' | sort -u`
  set lno_pids = ($lno_pids $ltask_pids)
end
foreach task ($sno_kill)
  set stask_pids = `ssh $sserver lsof | grep $USER | grep $task | awk '{print $2}' | sort -u`
  set sno_pids = ($sno_pids $stask_pids)
end
foreach task ($dno_kill)
  set dtask_pids = `ssh $dserver /usr/sbin/lsof | grep $USER | grep $task | awk '{print $2}' | sort -u`
  set dno_pids = ($dno_pids $dtask_pids)
end
#-----------------------------------------------------------------------------
# find all tools attached to the VNC sessions
set tpid_list = ()
set apid_list = ()
set lpid_list = ()
set spid_list = ()
set dpid_list = ()
foreach port ( $ports )
  set portnum  = `echo $port  | cut -f2 -d":"`
  if ($portnum < 10 ) then
    set portnum = 0$portnum
  endif
  set search = ${vnchost}:60${portnum}
  # kNserver tasks
#  set telpids = `rsh -l $telacct $telserv lsof | grep $telacct | grep $search | awk '{print $2}' | sort -u`
#  set tpid_list = ($tpid_list $telpids)
  # kNaoserver tasks
  set aopids = `rsh -l $aoacct $aoserver lsof | grep $aoacct | grep $search | awk '{print $2}' | sort -u`
  set apid_list = ($apid_list $aopids)
  # kNlaserserver tasks
#  set lpids = `rsh -l $lacct $lserver lsof | grep $lacct | grep $search | awk '{print $2}' | sort -u`
#  set lpid_list = ($lpid_list $lpids)
  # osirisserver tasks
  set spids = `ssh $sserver lsof | grep $USER | grep $search | awk '{print $2}' | sort -u`
  set spid_list = ($spid_list $spids)
end
# osirisdrp tasks
# linux reports connections differently than solaris so we only see connections
set search = ESTABLISHED
set dpids = `ssh $dserver /usr/sbin/lsof | grep $USER | grep $search | awk '{print $2}' | sort -u`
set dpid_list = ($dpid_list $dpids)

#-----------------------------------------------------------------------------
# check pid_lists against the no_kill lists, then build kill_lists
set tkill_list = ()
set akill_list = ()
set lkill_list = ()
set skill_list = ()
set dkill_list = ()

# tel
if ($#tno_kill > 0 ) then
  foreach p ($tpid_list)
    set count = 0
    foreach n ($tno_pids)
      if ( $p == $n ) then
        @ count++
      endif
    end
    if ( $count == 0 ) then
      set tkill_list = ($tkill_list $p)
    endif
  end
else 
  set tkill_list = ($tpid_list)
endif
# ao
if ($#ano_kill > 0 ) then
  foreach p ($apid_list)
    set count = 0
    foreach n ($ano_pids)
      if ( $p == $n ) then
        @ count++
      endif
    end
    if ( $count == 0 ) then
      set akill_list = ($akill_list $p)
    endif
  end
else 
  set akill_list = ($apid_list)
endif
# laser
if ($#lno_kill > 0 ) then
  foreach p ($lpid_list)
    set count = 0
    foreach n ($lno_pids)
      if ( $p == $n ) then
        @ count++
      endif
    end
    if ( $count == 0 ) then
      set lkill_list = ($lkill_list $p)
    endif
  end
else 
  set lkill_list = ($lpid_list)
endif
# osirisserver
if ($#sno_kill > 0 ) then
  foreach p ($spid_list)
    set count = 0
    foreach n ($sno_pids)
      if ( $p == $n ) then
        @ count++
      endif
    end
    if ( $count == 0 ) then
      set skill_list = ($skill_list $p)
    endif
  end
else 
  set skill_list = ($spid_list)
endif
# osirisdrp
if ($#dno_kill > 0 ) then
  foreach p ($dpid_list)
    set count = 0
    foreach n ($dno_pids)
      if ( $p == $n ) then
        @ count++
      endif
    end
    if ( $count == 0 ) then
      set dkill_list = ($dkill_list $p)
    endif
  end
else 
  set dkill_list = ($dpid_list)
endif

# Now kill the tasks
if ( $#tkill_list > 0 ) then
 $cmdpre rsh -l $telacct $telserv kill -9 $tkill_list
endif
if ( $#akill_list > 0 ) then
 $cmdpre rsh -l $aoacct $aoserver kill -9 $akill_list
endif
if ( $#lkill_list > 0 ) then
 $cmdpre rsh -l $lacct $lserver kill -9 $lkill_list
endif
if ( $#skill_list > 0 ) then
 $cmdpre ssh $sserver kill -9 $skill_list
endif
if ( $#dkill_list > 0 ) then
 $cmdpre ssh $dserver kill -9 $dkill_list
endif

goto done

abort:
# Block of code to handle interrupts.
exit 1

done:
# is there anything that needs to go here?
exit
