#! /bin/sh

### BEGIN INIT INFO
# Provides:          samba-ad-dc
# Required-Start:    $network $local_fs $remote_fs
# Required-Stop:     $network $local_fs $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: start Samba daemons for the AD DC
### END INIT INFO

#
# Start/stops the Samba daemon (samba).
# Adapted from the Samba 3 packages.
#

PIDDIR=/var/run/samba
SAMBAPID=$PIDDIR/samba.pid

# clear conflicting settings from the environment
unset TMPDIR

# See if the daemon and the config file are there
test -x /usr/sbin/samba -a -r /etc/samba/smb.conf || exit 0

. /lib/lsb/init-functions

case "$1" in
	start)
		SERVER_ROLE=`samba-tool testparm --parameter-name="server role"  2>/dev/null | tail -1`
		if [ "$SERVER_ROLE" != "active directory domain controller" ]; then
		    exit 0
		fi

		if init_is_upstart; then
			exit 1
		fi

		# CVE-2013-4475
		KEYFILE=/var/lib/samba/private/tls/key.pem
		if [ -e $KEYFILE ]
		then
				KEYPERMS=`stat -c %a $KEYFILE`
				if [ "$KEYPERMS" != "600" ]
				then
						echo "wrong permission on $KEYFILE, must be 600"
						echo "samba will not start (CVE-2013-4475)"
						echo "Removing all tls .pem files will cause an auto-regeneration with the correct permissions."
						exit 1
				fi
		fi

		log_daemon_msg "Starting Samba AD DC daemon" "samba"
		# Make sure we have our PIDDIR, even if it's on a tmpfs
		install -o root -g root -m 755 -d $PIDDIR

		if ! start-stop-daemon --start --quiet --oknodo --exec /usr/sbin/samba -- -D; then
			log_end_msg 1
			exit 1
		fi

		log_end_msg 0
		;;
	stop)
		if init_is_upstart; then
			exit 0
		fi
		log_daemon_msg "Stopping Samba AD DC daemon" "samba"

		start-stop-daemon --stop --quiet --pidfile $SAMBAPID
		# Wait a little and remove stale PID file
		sleep 1
		if [ -f $SAMBAPID ] && ! ps h `cat $SAMBAPID` > /dev/null
		then
			# Stale PID file (samba was succesfully stopped),
			# remove it (should be removed by samba itself IMHO.)
			rm -f $SAMBAPID
		fi

		log_end_msg 0

		;;
	restart|force-reload)
		if init_is_upstart; then
			exit 1
		fi
		$0 stop
		sleep 1
		$0 start
		;;
	status)
		status_of_proc -p $SAMBAPID /usr/sbin/samba samba
		exit $?
		;;
	*)
		echo "Usage: /etc/init.d/samba-ad-dc {start|stop|restart|force-reload|status}"
		exit 1
		;;
esac

exit 0