#!/bin/sh

source /etc/sysconfig/config
source /etc/sysconfig/helpers/functions

FSTAB="/etc/fstab";

IS_ON=/bin/chkconfig
CHKDEV=nfs

if [ "X${CONFIG_NETWORK_ENABLE}" != "Xy" ]
then
	exit 0;
fi

ERR=0;
case "$1" in
    "start")

		echo -ne "Starting NFS ... "
		if ! $IS_ON $CHKDEV
		then
			echo "disabled"
			exit 0
		fi
		# if network is off don'try to start either
		if ! $IS_ON network
		then
			echo "disabled"
			exit 0
		fi

        count=$(grep -c -e '[^ \t]*[ \t]*[^ \t]*[ \t]*nfs[ \t]*.*' ${FSTAB})
        if [ "X${count}" = "X0" ]; then
            echo "No NFS drives found, skip NFS init ... ";
            exit 0;
        fi
        echo "Found ${count} NFS drives ... ";
        if [ ! -r /proc/net/rpc/nfs ]; then 
            load_module nfs
            if [ "X$?" != "X0" ]; then ERR=1; fi
        fi
        /sbin/portmap;
        if [ "X$?" != "X0" ]; then ERR=2; fi
        for fstabentry in $(grep -e '[^ \t]*[ \t]*[^ \t]*[ \t]*nfs[ \t]*.*' ${FSTAB} | sed -e 's/\([^ ]*\).*/\1/'); do
            /bin/mount ${fstabentry};
            if [ "X$?" != "X0" ]; then ERR=3; fi;
        done
		echo "done"
        ;;
    "stop")
        count=$(mount -t nfs | grep -c nfs)
        if [ "X${count}" = "X0" ]; then
            echo "No NFS drives mounted ... ";
            exit 0;
        fi
        echo "Unmounting ${count} NFS drives ... ";
        for nfsentry in "$(mount -t nfs | sed -e 's/[^ ]*[ ]*on[ ]*\([^ ]*\).*/\1/')"; do
            /bin/umount ${nfsentry};
            if [ "X$?" != "X0" ]; then ERR=4; fi
        done
        /usr/bin/killall portmap;
        if [ "X$?" != "X0" ]; then ERR=5; fi
        ;;
    *)
        echo "Syntax is $0 start | stop"
        exit 255;
        ;;
esac

exit ${ERR};
