# !/bin/bash
#
# Start up netbeui & samba daemons
#
# by Philip Nienhuis, 22 Jun 03 / last update 29 Jun 03
#
# description: Start up NETBEUI and Samba daemons
#
# Some decisions are based on NETBEUI present in the kernel name (e.g.,
# 2.4.19-NETBEUI or the like)

case "$1" in
  start)
	# First some checks to see if netbeui is supported by kernel
	if ( uname -r |  egrep "NETBEUI" > /dev/null) ; then
		# Proper kernel is loaded, proceed.
		echo "Loading NETBEUI modules"
		modprobe netbeui autobind=1
		echo "Starting Samba daemons"
		/usr/local/bin/smbd -D -Z NETBEUI
		/usr/local/bin/nmbd -D -Z NETBEUI
	else
		gprintf "No NETBEUI support in kernel, NETBEUI skipped." 
	fi
	;;
  stop)
	# First some checks to see if netbeui is supported by kernel
	if ( uname -r |  egrep "NETBEUI" > /dev/null) ; then
		# Proper kernel is loaded, proceed.
		# Unload smbd and nmbd
		echo -n "Stopping samba daemons: smbd... "
		# Find smbd & nmbd pid's using a bit of trickery. First smbd daemon:
		RETVAL=0
		RETVAL=$(ps ax | egrep smbd | sort -r | awk '{ pid = 0 } $3 == "S" || $2 == "?" { pid += $1 } END { print pid } ');
		if [ $RETVAL -ne 0 ]; then
			kill -9 $RETVAL
			echo -n "done; "
		fi
		# nmbd daemon
		echo -n "nmbd..."
		RETVAL=0
		RETVAL=$(ps ax | egrep nmbd | sort -r | awk '{ pid = 0 } $3 == "S" || $2 == "?" { pid += $1 } END { print pid } ');
		if [ $RETVAL -ne 0 ]; then
			kill -9 $RETVAL
			echo " done."
		fi
		# Now unload netbeui kernel modules
		echo -n "Unloading netbeui kernel modules ... "
		#
		# Include a little delay to allow the smbd/nmbd shutdown
		# info to slowly trickle down to the netbeui modules
		sleep 2
		modprobe -r netbeui > /dev/null 2> /dev/null
		echo "Done."
	else
		gprintf "No NETBEUI support in kernel, NETBEUI skipped." 
	fi
	;;
  restart)
	$0 stop
	$1 start
	;;
  *)
	echo "Usage: netbeui <start | stop | restart> \n"
esac
