#!/bin/bash

PROGRAM=/bin/false
RUNLEVEL=3
NEEDS="+remote_fs +network +portmap"

. /etc/init.d/smgl_init
. /etc/sysconfig/nfs

if [ ! -e /etc/exports ] ; then
  $FAILURE
  echo "Please create an /etc/exports file. Exiting without starting nfs..."
  $NORMAL
  exit 1
fi

# may be outsourced
get_kernel_pids()
{
  local rval=1
  for pid in $(pidof $1)
  do
    if [[ -z $(</proc/$pid/cmdline) ]]; then
      builtin echo $pid
      rval=0
    fi
  done
  return $rval
}

start()
{
  echo "Starting full NFS services (server & locking)"
  # why do we reexport before the daemons are up?
  # doesn't seem to matter much
  required_executable /usr/sbin/exportfs
  echo -n "exportfs"
  /usr/sbin/exportfs -r 
  evaluate_retval

  # nfs-howto says: these daemons in this order
  # userspace does not bother about lockd since linux 2.2.18
  for d in mountd nfsd statd rquotad
  do
    required_executable /usr/sbin/rpc.$d
    local opts=
    if   [[ $d == mountd ]]; then opts="$MOUNTDOPTS"
	  if  [[ ! -z "$MOUNTD_PORT" ]]; then opts="$opts -p $MOUNTD_PORT"
	  fi
    elif [[ $d == nfsd ]]; then opts="$NUMSERVERS"
	elif [[ $d == statd && ! -z $STATD_PORT ]]; then opts="-p $STATD_PORT"
    fi
    echo -n $d
    loadproc /usr/sbin/rpc.$d $opts
  done
}

stop()
{
  echo "Stopping NFS services"
  echo -n "unexporting filesystems"
  /usr/sbin/exportfs -au
  evaluate_retval
  
  # all in one loop to simplify code, reversed order
  # atm. only nfsd is really in-kernel (and lockd self-managed)
  for d in rquotad statd nfsd mountd
  do
    local kpid=$(get_kernel_pids $d)
    if [[ -z $kpid ]]; then
      echo -n "killing $d"
      killproc /usr/sbin/rpc.$d
    else
      echo "not killing kernel $d (PID $kpid)"
    fi
    echo "Removing kernel nfsd"
    /usr/sbin/rpc.nfsd 0
  done
}

status()
{
  for d in mountd nfsd statd rquotad
  do
    local kpid=$(get_kernel_pids $d)
    [[ -n $kpid ]] && echo "kernel $d there with PIDs $kpid" ||
    statusproc /usr/sbin/rpc.$d
  done
  echo -n "kernel lockd "
  kpid=$(get_kernel_pids lockd)
  [[ -n $kpid ]] && echo "is active (PID $kpid)" || echo "is not active (but hopefully ready)" 
}
