#!/usr/bin/perl -w

use Getopt::Long;
use POSIX "sys_wait_h";

#globals
my $session_file;
my %config;
my $rc = 0;
my $pid;

if (init()) {
    exit 1;
}

if ($config{'MOUNT_FS'} == 1) {
	$rc = stop_fs_mount(\%config);
	if ($rc) {
		print STDERR "WARNING: mount cleanup failed...$rc\n";
	}
}

#stop iods
$rc = stop_servers(\%config);
if ($rc) {
    print STDERR "WARNING: server stop failed...$rc\n";
}

exit(0);

sub stop_fs_mount {
    my $href = shift;

    my @nodes = ();
    my $rc = 0;

    @nodes = @{$href->{'COMPNODES'}};

    my $cmd = "%node umount $href->{'MOUNTPOINT'}";
    $rc = do_remote_command($href->{'RCMDPROG_ROOT'}, 8, 30, $cmd, undef, undef, @nodes);

    $cmd = "%node killall pvfs2-client\\\; sleep 5\\\; killall -9 pvfs2-client";
    $rc = do_remote_command($href->{'RCMDPROG_ROOT'}, 8, 30, $cmd, undef, undef, @nodes);

    $cmd = "%node /sbin/rmmod $href->{'PVFS_KMOD'}";
    $rc = do_remote_command($href->{'RCMDPROG_ROOT'}, 8, 30, $cmd, undef, undef, @nodes);

    return ($rc);
}


sub stop_servers {
    my $href = shift;

    my @servers = (@{$href->{'MGR'}}, @{$href->{'IONODES'}});
    my $rc = 0;

    # a bit viscious, but we don't store our pid anywhere 
    my $cmd = "%node killall pvfs2-server \\\; sleep 1 \\\; killall -9 pvfs2-server";
   
    $rc = do_remote_command($href->{'RCMDPROG'}, 8, 30, $cmd, undef, undef, @servers);

    return($rc);
}

sub usage {

    print<<EOF;
Usage: $prog_name [option]
-s -session       session file for PAV to use
-sd -sessiondir   directory containing session file 'pvfs_autosession'
-rsh              remote shell command to use (default 'ssh')
-rcp              remote copy command to use (default 'scp')
-h -help          display this message
EOF
}

sub init {
    GetOptions(\%args,
	       's|session:s',
	       'sd|sessiondir:s',
	       'rsh:s',
	       'rcp:s',
	       'r|root:s',
	       'h|help'
	       );

    if ($args{'h'}) {
	usage();
	return(1);
    }

    if ($args{'s'}) {
	$session_file = $args{'s'};
    } elsif ($args{'sd'}) {
	$session_file = $args{'sd'} . "/pvfs_autosession";
    } else {
	usage();
	return(1);
    }

    if (!-f $session_file) {
	print STDERR "ERROR: cannot find session file: $session_file\n";
	return(1);
    }

    %config = ('RCMDPROG' => "ssh",
	       'RCPPROG' => "scp",
	       'PROGROOT' => "./"
	       );

    $config{'PROGROOT'} = $args{'r'} || $config{'PROGROOT'};
    my $prog_root = $config{'PROGROOT'};
    require "$prog_root/pav_lib.pl";

    $rc = read_sessionfile($session_file, \%config);
    if ($rc) {
	print STDERR "ERROR: cannot read session file\n";
	return(1);
    }

    $config{'RCMDPROG'} = $args{'rsh'} || $config{'RCMDPROG'};
    $config{'RCPPROG'} = $args{'rcp'} || $config{'RCPPROG'};

    $prog_name = $0;
    $pid = $$;

    return(0);
}
