#!/bin/bash

# Repeatedly copy files to NFS server.

# Copyright (C) 2003-2006 IBM
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
# 02111-1307, USA.

if [ -z "$NFS_SERVER" -o "$NFS_SERVER" == "0" ]; then
	echo "NFS server not configured."
	exit 255
fi

SHORTHOST=`echo "$HOSTNAME" | sed -e 's/\..*//g'`

# set up to delete nfs data and unmount nfs when we die
NFSMOUNT=/pounder
NFSLOCAL="$POUNDER_TMPDIR/nfs-$$"
trap 'echo Cleaning up...; mv $NFSLOCAL/$SHORTHOST/testnet $NFSLOCAL/$SHORTHOST/testnet.del; rm -rf $NFSLOCAL/$SHORTHOST/testnet.del; umount $NFSLOCAL; rm -rf $NFSLOCAL; echo Clean.; exit 0' 1 2 15

[ ! -x $NFSLOCAL ] && mkdir $NFSLOCAL
echo "Mounting remote storage via NFS..."

echo Mounting $NFS_SERVER:$NFSMOUNT on $NFSLOCAL...

# Did we see any failures?
LOGFILE=/proc/$$/fd/1
OLD_ERRORS=`egrep -ic "(err|fail|cannot|invalid|denied)" $LOGFILE`

if (mount "$NFS_SERVER:$NFSMOUNT" $NFSLOCAL -t nfs -o tcp); then
	# Create a dir for this machine and sleep to give our mkdir a
	# better chance of making it.
	[ ! -x $NFSLOCAL/$SHORTHOST ] && mkdir $NFSLOCAL/$SHORTHOST
	sleep 5

	# If we've already stuff here, move it and delete it.
	# Meanwhile, create ourselves a new directory for the copy
	[ -x $NFSLOCAL/$SHORTHOST/testnet ] && \
		mv $NFSLOCAL/$SHORTHOST/testnet $NFSLOCAL/$SHORTHOST/testnet.del
	[ -x $NFSLOCAL/$SHORTHOST/testnet.del ] && \
		rm -rf $NFSLOCAL/$SHORTHOST/testnet.del &

	# Actually copy data...
	echo "Remote NFS copy in progress..."
	cp -pr /usr $NFSLOCAL/$SHORTHOST/testnet

	# Now diff it...
	diff -Naur /usr $NFSLOCAL/$SHORTHOST/testnet > $POUNDER_TMPDIR/nfs.diff

	# Now remove it
	rm -rf $NFSLOCAL/$SHORTHOST/testnet

	# and unmount
	umount $NFSLOCAL
	rm -rf $NFSLOCAL
else
	echo Unable to connect to the NFS server $NFS_SERVER.
	echo Please check network configuration and update the script.
	exit -1
fi

# Anything in the diff?
DIFF_ERRORS=`wc -l < $POUNDER_TMPDIR/nfs.diff`
if [ $DIFF_ERRORS -gt 0 ]; then
	exit $DIFF_ERRORS
fi

# Did we see any failures?
NEW_ERRORS=`egrep -ic "(err|fail|cannot|invalid|denied)" $LOGFILE`
ERRORS=$((NEW_ERRORS - OLD_ERRORS))
if [ $ERRORS -eq 255 ]; then
        ERRORS=254
fi
exit $ERRORS