#!/usr/bin/env 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
#
#####################################################

if (!$ENV{'NFSSERVER'})
{
    `logger -t xcat "environment variable does not exist, exiting..."`;
     exit;
}

my $nfsserver = $ENV{'NFSSERVER'};

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

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)
    {
        next;
    }
    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 xcat "runcmd $cmd failed, error message is:"`;
            my $errmsg;
            foreach my $err (@::outref)
            {
                $errmsg .= $err;
            }
            `logger -t xcat "$errmsg"`;
             exit;
        }
    }
    return $rc;
}
