#!/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;
}

#clean out working dir
$rc = remove_remotedirs(\%config);
if ($rc) {
    print "WARNING: remove dir failed on node $rc\n";
}
#done

exit(0);

sub remove_remotedirs {
    my $href = shift;
    my @ionodes = @{$href->{'IONODES'}};
    my @compnodes = @{$href->{'COMPNODES'}};
    my @metas   = @{$href->{'MGR'}};
    my $rc = 0;

    my $working_dir = $href->{'WORKINGDIR'};

    if ($config{'USERNAME'} eq "root") {
	print "WARNING: running as root, will be removing '$working_dir', are you sure you want to continue? (y/n): ";
	chomp(my $yorn = <STDIN>);
	if ($yorn =~ /n/i) {
	    return(1);
	}
    }

    my $cmd = "%node rm -rf $working_dir";
    my @nodes = (@ionodes, @compnodes, @metas);
    $rc = do_remote_command($href->{'RCMDPROG'}, 8, 30, $cmd, undef, undef, @nodes);

    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);
}

