#!/bin/bash
#
# rpcgssd       Start up and shut down RPCSEC GSS daemon
#
# Authors:    Chuck Lever <cel@netapp.com>
#
# chkconfig: 345 19 85
# description: Starts user-level daemon that manages RPCSEC GSS contexts \
#           for the NFSv4 client.

# Source function library.
. /etc/init.d/functions

# Source networking configuration.
[ -f /etc/sysconfig/network ] && . /etc/sysconfig/network

# Check for and source configuration file otherwise set defaults
[ -f /etc/sysconfig/nfs ] && . /etc/sysconfig/nfs

# See if we are configured to start 
[ "${SECURE_NFS}" != "yes" ] && exit 6

# Try to use machine credentials by default
RETVAL=0
LOCKFILE=/var/lock/subsys/rpcgssd
prog="rpc.gssd"

case "$1" in
  start|condstart)
    # Check that networking is up.
    [ "${NETWORKING}" != "yes" ] && exit 6
    [ ! -x /usr/sbin/rpc.gssd ] && exit 5

    # Make sure the daemon is not already running.
    if status $prog > /dev/null ; then
        exit 0
    fi

    # During condstart need to check again to see
    # if we are configured to start
    [ "${SECURE_NFS}" != "yes" ] && exit 6

    rm -f $LOCKFILE
    echo -n $"Starting RPC gssd: "

    # List of kernel modules to load
    [ -z "${SECURE_NFS_MODS}" ] && SECURE_NFS_MODS="des rpcsec_gss_krb5"

    # Make sure the rpc_pipefs filesystem is available
    [ "${RPCMTAB}" != "noload" ] && {
        RPCMTAB=`grep -v '^#' /proc/mounts | \
            awk '{ if ($3 ~ /^rpc_pipefs$/ ) print $2}'`
        [ -z "${RPCMTAB}" ] && {
            [ -x /sbin/lsmod -a -x /sbin/modprobe ] && {
                if ! /sbin/lsmod | grep sunrpc > /dev/null ; then
                     /sbin/modprobe sunrpc
                fi
            }
            RPCMTAB=`grep -v '^#' /proc/mounts | \
                awk '{ if ($3 ~ /^rpc_pipefs$/ ) print $2}'`
            [ -z "${RPCMTAB}" ] && { \
                echo "Error: RPC MTAB does not exist."
                exit 6
            }
        }
    }
    [ "${SECURE_NFS_MODS}" != "noload" ] && {
        [ -x /sbin/lsmod -a -x /sbin/modprobe ] && {
            for i in ${SECURE_NFS_MODS}; do 
                if ! /sbin/lsmod | grep $i > /dev/null ;  then
                     /sbin/modprobe $i || {
                        echo "Error: Unable to load '$i' security module."
                        exit 6;
                    }
                fi
            done
        }
    }

    # Start daemon.
    daemon $prog ${RPCGSSDARGS}
    RETVAL=$?
    echo
    [ $RETVAL -eq 0 ] && touch $LOCKFILE
    ;;
  stop)
    # Stop daemon.
    echo -n $"Stopping RPC gssd: "
    killproc $prog
    RETVAL=$?
    echo
    [ $RETVAL -eq 0 ] && rm -f $LOCKFILE
    ;;
  status)
    status rpc.gssd
    RETVAL=$?
    ;;
  restart|reload)
    $0 stop
    $0 start
    RETVAL=$?
    ;;
  condrestart)
    if [ -f $LOCKFILE ]; then
        $0 restart
        RETVAL=$?
    fi
    ;;
  *)
    echo $"Usage: $0 {start|stop|restart|condstart|condrestart|status}"
    RETVAL=3
    ;;
esac

exit $RETVAL