#!/usr/bin/perl
# IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html
#####################################################
#
#   xCAT post script for diskless nodes
#   to redirect paging space to external NFS server,
#   which is specified through nfsserver attribute
#
#####################################################
my $log_label=$ENV{'LOGLABEL'};
if (!$log_label) {
    $log_label="xcat"
}
if (!$ENV{'NFSSERVER'})
{
`logger -t $log_label -p local4.err "environment variable does not exist, exiting..."`;
    exit -1;
}

my $nfsserver   = $ENV{'NFSSERVER'};
my @ps          = ();
my @nfsserverps = ();

my $cmd = "lsps -t nfs -c";
&runcmd($cmd);

# Remove any inactive paging space from external nfs server first
foreach my $line (@::outref)
{
    chomp($line);
    if ($line =~ /^#/)
    {
        next;
    }
    my ($psname, $pshost, $psfile, $pssize, $psused, $psactive, $psauto, $pstype, $pschksum) = split(/:/, $line);
    if ($pshost eq $nfsserver)
    {
        if ($psactive eq 'n')
        {
            # Inactive paging space, remove it
            $cmd = "rmps $psname";
            &runcmd($cmd);
        }
        else
        {
            push @nfsserverps, $psfile
        }
    }
    else
    {
        push @ps, $line;
    }
}

foreach my $psline (@ps)
{
    my ($psname, $pshost, $psfile, $pssize, $psused, $psactive, $psauto, $pstype, $pschksum) = split(/:/, $psline);
    if ($pshost eq $nfsserver)
    {
        next;
    }

    if (!grep(/^$psfile$/, @nfsserverps))
    {
        my $cmd = "mkps -a -n -t nfs $nfsserver $psfile";
        &runcmd($cmd);
    }
    $cmd = "swapoff /dev/$psname";
    &runcmd($cmd);

    $cmd = "rmps $psname";
    &runcmd($cmd);
}

sub runcmd
{
    my ($cmd) = @_;
    my $rc = 0;
    $cmd .= ' 2>&1';
    @::outref = `$cmd`;
    if ($?)
    {
        $rc = $? >> 8;
        if ($rc > 0)
        {
`logger -t $log_label -p local4.err  "runcmd $cmd failed, error message is:"`;
            my $errmsg;
            foreach my $err (@::outref)
            {
                $errmsg .= $err;
            }
            `logger -t $log_label  -p local4.err "$errmsg"`;
            exit -1;
        }
    }
    return $rc;
}

exit 0;
