#!/bin/sh
#
#	Written by Eloy A. Paris <peloy@debian.org> for Debian GNU/Linux.
#

PATH="/usr/sbin:/usr/bin:/sbin:/bin"

while [ $# -gt 0 ]
do
	case "$1" in
		--run-from-inetd)
			run_from_inetd=1
			shift
		;;

		--run-as-daemons)
			run_from_inetd=0
			shift
		;;

		*)
			echo "Usage: $0 [--run-from-inetd|--run-as-daemons]" >&2
			exit 1
		;;
	esac
done

# Make sure there are no Samba daemons (nmbd or smbd) running
#

if grep -q '^netbios-ns' /etc/inetd.conf; then
	# Samba is running from inetd - need to disable inetd before
	#	killing the daemons.
	update-inetd --disable netbios-ssn
	update-inetd --disable netbios-ns
	start-stop-daemon --stop --user root --name nmbd --quiet
	start-stop-daemon --stop --user root --name smbd --quiet
else
	# Samba is running as daemons
	/etc/init.d/samba stop
fi

if [ "x$run_from_inetd" = "x" ]
then
	echo "Run Samba as daemons or from inetd?"
	echo -n "Press 'D' for to run as daemons or 'I' to run from inetd: [I] "

	read mode
	test -n "$mode" || mode="I"

	case "$mode" in
		[Dd]*)
			echo "Samba will run as daemons. Run sambaconfig to reconfigure"
			update-inetd --disable netbios-ssn
			update-inetd --disable netbios-ns
		;;

		*)
			echo "Samba will run from inetd. Run sambaconfig to reconfigure"
			update-inetd --enable netbios-ssn
			update-inetd --enable netbios-ns
		;;
	esac
elif [ $run_from_inetd = 1 ]; then
	update-inetd --enable netbios-ssn
	update-inetd --enable netbios-ns
else
	update-inetd --disable netbios-ssn
	update-inetd --disable netbios-ns
fi

# Start daemons (nothing wrong will happen if Samba is running as daemons,
#	/etc/init.d/samba takes care of that.

/etc/init.d/samba start
