#! /bin/sh 
#

smbd=/usr/sbin/smbd
test -x "$smbd" || exit 0

nmbd=/usr/sbin/nmbd
test -x "$nmbd" || exit 0

wsdd=/usr/sbin/wsdd
test -x "$wsdd" && WSDD_DISABLED="No" || WSDD_DISABLED="Yes"


check_pam() {
	grep -q 'pam_smbpass.so' /etc/pam.d/common-password
	if [ $? -eq 0 ] ; then
		echo "[samba] samba is already registered for pam"
	else
		echo "[samba] registering samba at pam"
		echo -e "password\toptional\t\t\tpam_smbpass.so nullok use_authtok use_first_pass" >> $D/etc/pam.d/common-password
	fi
}

check_default_pwd() {

[ -e /etc/samba/private/smbpasswd ] || touch /etc/samba/private/smbpasswd
grep -q '^root:' /etc/samba/private/smbpasswd
if [[ $? -eq 0 ]] ; then
        echo "[samba] root user also available in samba password DB"
else
        smbpasswd -Ln root >/dev/null
fi


}

case "$1" in
	start)
		check_default_pwd
		echo "[samba] starting services"
		echo -n "[samba] starting: smbd"
		start-stop-daemon --start --quiet --exec $smbd
		NMBD_DISABLED=`testparm -s --parameter-name='disable netbios' 2>/dev/null || true`
		if [ "$NMBD_DISABLED" != "Yes" ]; then
			echo -n " nmbd"
			start-stop-daemon --start --quiet --exec $nmbd
		fi
		if [ "$WSDD_DISABLED" != "Yes" ]; then
			echo -n " wsdd"
			start-stop-daemon --start --quiet --exec $wsdd
		fi
		echo "."
		;;
	stop)
		echo -n "[samba] stopping: smbd"
		start-stop-daemon --stop --quiet --pidfile /var/run/smbd.pid
		NMBD_DISABLED=`testparm -s --parameter-name='disable netbios' 2>/dev/null || true`
		if [ "$NMBD_DISABLED" != "Yes" ]; then
			echo -n " nmbd"
			start-stop-daemon --stop --quiet --pidfile /var/run/nmbd.pid
		fi
		if [ "$WSDD_DISABLED" != "Yes" ]; then
			echo -n " wsdd"
			start-stop-daemon --stop --quiet --pidfile /var/run/wsdd.pid
		fi
		echo "."
		;;
	reload|force-reload)
		if [ "$WSDD_DISABLED" != "Yes" ]; then
			start-stop-daemon --stop --quiet --pidfile /var/run/wsdd.pid
		fi
		start-stop-daemon --stop --quiet --signal 1 --exec $smbd
		NMBD_DISABLED=`testparm -s --parameter-name='disable netbios' 2>/dev/null || true`
		if [ "$NMBD_DISABLED" != "Yes" ]; then
			start-stop-daemon --stop --quiet --signal 1 --exec $nmbd
		fi
		if [ "$WSDD_DISABLED" != "Yes" ]; then
			sleep 1
			start-stop-daemon --start --quiet --exec $wsdd
		fi
		;;
	restart)
		$0 stop;
		echo -n "[samba] stopping services"
		for i in 1 2 3 ; do
			sleep 1
			echo -n "."
		done
		echo ""
		$0 start;
		;;
	*)
		echo "Usage: /etc/init.d/samba {start|stop|reload|restart|force-reload}"
		exit 1
esac

exit 0

