#!/usr/bin/env perl
#
# Copyright (c) 2001-2007 CNRS/LAAS
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

#
# Kill a Genom module running under a Unix system
#
# Matthieu Herrb - Fevrier 2001
#
#----------------------------------------------------------------------
#
# Check arguments
if ($#ARGV != 0) {
  print STDERR "syntaxe: $0 <module>\n";
  exit -1;
}
$module = $ARGV[0];
# host name
$host = `uname -n`;
chop $host;
# instance 
$instance = $ENV{"GENOM_INSTANCE_$module"};
if (defined($instance)) {
    $module = "$module$instance";
}
# name of the file holding the process id
$h2owner = $ENV{'H2DEV_DIR'};
if (defined($h2owner)) {
  $pid_file = "$h2owner/.$module.pid-$host";
} else {
  $pid_file = "$ENV{'HOME'}/.$module.pid-$host";
}
$me = $ENV{'USER'};
# Check its existence
if ( ! -f $pid_file) {
  print STDERR "$0: the module $module doesn't seem to be running on $host\n";
  print STDERR "$0: no file $pid_file\n";
  exit 1;
}
# Check the owner of the file
$uid = (stat($pid_file))[4];	# numerical uid of the file
$name = (getpwuid($uid))[0];	# get the actual user name
if ( $me ne $name ) {
  print STDERR "$0: the $module process is owned by $name (not $me)\n";
  exit -1;
}
# Read the file
open PID,"<$pid_file" || die "can't read $pid_file";
$pid = <PID>;
if (!defined($pid)) {
  # Empty file
  print "No pid in $pid_file\n";
  unlink("$pid_file");
  # Clean up pocolib devices of the module
  system("h2 clean '*$module*'");
  exit 0;
}
print "pid ".$pid;
chop $pid;
close PID;

# Check if process still alive
if (kill(0, $pid) == 0) {
  # no more process
  print("$module seems to be dead already, cleaning up\n");
  unlink("$pid_file");
  system("h2 clean '*$module*'");
  exit(0);
}
# send SIGTERM 
kill 15, $pid;

# Wait a bit for the module to die cleanly
$now = time();
do {
  select(undef, undef, undef, 0.5);
} while (-f $pid_file && time() < $now + 10);

# if file still there, use SIGINT
if (-f $pid_file) {
  print("$module takes too long to die, sending SIGINT\n");
  kill 2, $pid;
  # wait
  select(undef, undef, undef, 3.0);
  
  # Remove the pid file
  if (-f $pid_file) {
    unlink("$pid_file");
  }
  # Clean up pocolib devices of the module
  system("h2 clean '*$module*'");
} else {
  print("done\n");
}
# done
exit 0;
