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