#!/usr/local/bin/perl
#
#  Selectively kills processes from a group of hosts 
#
#  Rajitha Sumanasekera
#  rajitha@dcs.uky.edy
#  Aug 02, 1997 
#
#  Note: Uses a .SECrc file with host groups.
#
#  Sample host file:
#       =DCS
#       clarinet.dcs
#       violin.dcs
#

if (@ARGV  >= 1) {
  $ttype = $ARGV[0];
  $proc = $ARGV[1];
} else {
  @groups = &get_groups;
  print("\n    Usage: kill_procs [group] [process]\n\n");  
  print("\tWhere group is one of:\n\t    @groups\n");
  die "\n";
}

if (get_host($ttype,1) eq "") {
  die "\n\tNo such host group\n\n";
}


print "\n";
while ($host = get_host($ttype, ++$n)) {
  if ($host eq "") {
    last;   
  }

  print("[ $host ]\n");
  @pids = &find_proc($host, $proc);

  if ($pids[0] eq "") {
    next;
  }
    
  system("rsh $host /bin/kill -9 @pids\n");
}

print "\n";


sub get_groups {
  local(@groups, $num);
  chop($rcFile =`echo \$HOME`);
  $rcFile .= "/.SECrc";
  open(HOST, $rcFile) || die "can't find $rcFile\n";
  
  while (<HOST>) {
    s/\s+//;

    if ($_ =~ /\=/) {
      s/=//;
      $groups[$num++] = $_;      
    }
  }
  @groups;
}

sub get_host {
  chop($rcFile =`echo \$HOME`);
  $rcFile .= "/.SECrc";
  open(HOST, $rcFile) || die "can't find $rcFile\n";

  while (<HOST>) {
    s/\s+//;
    s/=//;
	
    if ($_ eq $_[0]) {
      last;
    }
  }

  $hostNum = 0;
  while ($host = <HOST>) {
    $host =~ s/\s+//;

    if ($host eq "") {
      next;
    }

    $hostNum++;
    if ($hostNum == $_[1]) {
      last;
    }
    $host ="";
  }

  if ($host =~ /\=/) {
      $host = "";
  }
  close(HOST);

  $host;
}

sub find_proc {
  local(@pids, $i, $whoami);
  chop($whoami =`whoami`);
  open(PS, "rsh $_[0] /bin/ps -ef |")  || warn "can't run ps\n";
  $head = <PS>;
  $COMMAND = index($head, "CMD") if $COMMAND <= 0;

  while (<PS>) {
    $pid = substr($_,9,6) + 0;
    if (index($_, $whoami) < 0 ) {
       next;
    } 
    if (index($_, "/bin/ps") >= 0) {
       next;
    }
 
    $cmd = substr($_,$COMMAND);
    chop($cmd);    
    if ($cmd =~ /^($_[1])/) {
      print("\tFound pid $pid: $cmd\n");
      $pids[$i++] = $pid;
    }
  }
  close(PS);
  @pids;
}

