#!/usr/bin/env perl 
#         C3 version 3.2 Cluster Command & Control Suite
#           Oak Ridge National Laboratory, Oak Ridge, TN,
#     Authors:  M.Brim, R.Flanery, G.A.Geist, B.Luethke, S.L.Scott
#                 (C) 2001 All Rights Reserved
# 
#                             NOTICE
# 
# Permission to use, copy, modify, and distribute this software and
# its documentation for any purpose and without fee is hereby granted
# provided that the above copyright notice appear in all copies and
# that both the copyright notice and this permission notice appear in
# supporting documentation.
# 
# Neither the Oak Ridge National Laboratory nor the Authors make any
# representations about the suitability of this software for any
# purpose.  This software is provided "as is" without express or
# implied warranty.
 
# The C3 tools were funded by the U.S. Department of Energy.
 

# ckillnode - used by ckill[s] to kill a process on a node
# Author: Brian Luethke 
# Last Updated: 03/19/2001#


# set version_number
$version_number="3.2";

# declare modules
use Getopt::Long;


# set version information
$version_info = <<"EOF";

ckillnode v$version_number

EOF

# set help information
$help_info = $version_info . <<"EOF";
Usage: ckillnode [OPTIONS] --signal=signal --process=processName 

	-h, --help 			: get this message
	-p, --process processName	: name of process to kill 
					  (not PID or job number)
	-s, --signal signal		: signal to send to process, same as 
					  standard 'kill'
	-u, --user username		: user name of the process owner 
					  (root user only)

EOF

# interpret command line options
GetOptions( "help|h",
	    "signal|s=s",
	    "process|p=s",
	    "user|u=s",
);

# if not enough arguments are given at the command line, 
# quit with the help message
if ( !$opt_signal ) {
	$opt_signal = "" }
else {
	$opt_signal = "-$opt_signal";}

if ( !$opt_process || $opt_help ) { die qq($help_info); };
if ( $opt_user  && $< != 0 ) { die "must be root to specify a user\n"; }


$opt_help =""; #this quites intepreter warnings


if( $opt_user ne "NONE" && $opt_user ne "ALL" ) {
  open( ETC_PASSWD, "< /etc/passwd" ) or die "couldn't open /etc/passwd\n";

  while (<ETC_PASSWD>) {
    chomp( $_ );
    if( $_ =~ /($opt_user):(.*):(.*):(.*):(.*):(.*):.(.*)/ ) {
      $uid = $3;
    }
  }
  if( !$uid ) { die "Could not find user $opt_user\n"; }
  close( ETC_PASSWD );
}

if( $opt_user eq "ALL" ) { $uid = ".*"; }

if( !$opt_user ) { $uid = $<; }



print "uid selected is $uid\n";

system ("ps -eo comm,pid,uid > /tmp/ps_temp_$<" );

open( PS_OUTPUT, "< /tmp/ps_temp_$<" ) or 
  die "couldn't open /tmp/ps_temp_$<\n";
while( <PS_OUTPUT> ) {
  if( $_ =~ /($opt_process\s+)(\w+)(\s+$uid)/ )   {
    system ( "kill $opt_signal $2" );
  }
}

exit( 0 );
