eval '(exit $?0)' && eval '[ -f /usr/local/bin/perl ] && exec /usr/local/bin/perl -S $0 ${1+"$@"}; exec perl -S $0 ${1+"$@"};'
& eval 'if ( -f /usr/local/bin/perl ) exec /usr/local/bin/perl -S $0 $argv:q ; exec perl -S $0 $argv:q'
     if 0;


# @(#)[Hyper-G] [HGS-C] dbstop	1.01 [stop server] [Gerald Pani]

# 
#<copyright>
# 
# Copyright (c) 1995
# Institute for Information Processing and Computer Supported New Media (IICM),
# Graz University of Technology, Austria.
# 
#</copyright>
  
#<file>
#
# Name:       dbstop.pl
#
# Purpose:    stops Hyper-G Server 
#
# Created:    21 Mar 95    Gerald Pani
# 
#</file>

$pname = &basename( $0);

$homedir = $ENV{'HOME'} || $ENV{'LOGDIR'} || (getpwuid($<))[7] 
    || &cleanup("You're homeless!\n");

$ACTIVE		= "ACTIVE";			# loop while file exists

# restart if .hgrc is't included
&checkHgrc();

# check directories
$DIRserver 	= &checkSetDir('DIRserver');

chdir( $DIRserver);

# check host
$DBHost = $ENV{'DBHost'};	# get from environ;
defined($DBHost) 		|| &cleanup("DBHost not set !\n");
chop($hostname = `hostname`);
$hostname eq $DBHost 		|| &cleanup("DBHost ($DBHost) not equal to $hostname!");


$pid = '';
if ( -f $ACTIVE ) {
    $pid = `cat $ACTIVE`;
}
unlink($ACTIVE);

$ret = system( "dbcontrol -S -r $DBHost");

if ($ret && $pid) {
    kill 'TERM', $pid;
    exit(0);
}

exit($ret>>8) if $ret;

$cnt = 10;
while ( -f 'LOCKDBCONTROL' && $cnt) {
    $cnt--;
    sleep(2);
}

if ( -f 'LOCKDBCONTROL' && $pid) {
    kill 'TERM', $pid;
}

exit(0);


# environment variables from ~/.hgrc should be set. One of them should
 # be 'HGRC'. If 'HGRC' isn't set, then include ~/.hgrc and restart
 # this program.
sub checkHgrc {
  return if defined( $ENV{'HGRC'});

  $ENV{'HGRC'} = '';
  &cleanup("Couldn't read $homedir/.hgrc\n") if (! -r "$homedir/.hgrc");
  exec( "/bin/csh -c \'(source $homedir/.hgrc ; $0)\'") ||
      &cleanup("exec: $!\n");
}

sub checkSetDir {
  local($envName) = @_;
  local($dir);
  $dir = $ENV{$envName};	# get from environ;
  defined($dir) 	|| &cleanup("$envName not set !\n");
  -d $dir 		|| &cleanup("$envName $dir is not a directory!\n");
  chdir($dir) 		|| &cleanup("Couldn't change into $dir!\n");
  (-o ".") 		|| &cleanup("User not owner of $dir!\n");
  return $dir;
}
 
# exit on error: print error message, terminate child processes and exit
sub cleanup {
  local($out) = @_;
  print STDERR "$pname: Error: ", $out;
  exit(1);
}

sub basename {
  local($path) = @_;
  
  return '' unless $path =~ m,(^|/)([^/]+)$,;
  return $2;
}
