#!/bin/sh

# $Id: samba.sh,v 1.1 2003/12/27 23:03:10 msolomon Exp $
#
# @author mike-web - at - culater - dot - net
# @description A basic control script for the Samba daemons smbd and nmbd.


logger -p daemon.alert "`basename ${0}` $*"

SSCF_PATH="/Library/Samba Sharing"
SSCF_EXT=".sscf"
SMB_CONF_FILE="/etc/smb.conf"

# path where the daemon
SAMBA_DAEMON_PATH="/usr/sbin"
SAMBA_PATH="/usr/bin"

# notification keys
NOTIFY_SETUP_CHANGE="Setup:/" # indicates that the location has changed
NOTIFY_IP_CHANGE="State:/Network/Global/IPv4" # indicates that the IP address has changed

function check_root()
{
	if [ `id -u` -ne 0 ]; then
		echo "Permission denied, root permissions required"
		exit 2
	fi
}

if [ "${1}" == "start" ]; then
	check_root
	echo "Starting Samba..."
	${SAMBA_DAEMON_PATH}/smbd -D
	${SAMBA_DAEMON_PATH}/nmbd -D
elif [ "${1}" == "stop" ];  then
	check_root
	echo "Stopping Samba..."
	# smbd and nmbd gracefully exit on SIGTERM
	ps -axco pid,command | awk '/smbd/ { print $1}' | xargs -n 1 kill
	ps -axco pid,command | awk '/nmbd/ { print $1}' | xargs -n 1 kill
elif [ "${1}" == "lsconfig" ];  then
	echo "Listing Samba configurations:"
	ls -1 "${SSCF_PATH}" | awk -F. '{print $1}'
elif [ "${1}" = "config" ]; then
	if [ ${#} -ne 2 ]; then
		"${0}" lsconfig
	else
		echo "Switching Samba config to ${2}"
		SSCF_FILE="${SSCF_PATH}/${2}${SSCF_EXT}"
		if [ -f "${SSCF_FILE}" ]; then
			ln -sf "${SSCF_FILE}" "${SMB_CONF_FILE}"
			# don't auto restart
			# "${0}" restart
		else
			echo "Error: ${SSCF_FILE} not found"
			exit 1
		fi
	fi
elif [ "${1}" == "status" ];  then
	echo "Samba Status"
	ps -axco command | grep -i "mbd"
	if [ $? -eq 0 ]; then
		${SAMBA_PATH}/smbstatus
	else
		echo "Samba is not running"
	fi
elif [ "${1}" == "restart" ];  then
	check_root
	echo "Restarting Samba..."
	"${0}" stop > /dev/null
	"${0}" start > /dev/null
elif [ "${1}" == ${NOTIFY_SETUP_CHANGE} ];  then
	# this was a setup change, find a matching config
	# wait for IP change to actually restart samba, since frequently the
	# adapter isn't in a "ready" state when this key is notified
	BASENAME=`basename "${0}"`
	TEMP_CONFIG_NAME="/tmp/${BASENAME}.$$"
	scutil <<- scutil_end | awk 'BEGIN { FS = " : "} /UserDefinedName/ { print $2 } END { }' > ${TEMP_CONFIG_NAME}
		open
		get Setup:/
		d.show
		close
	scutil_end
	CONFIG_NAME=`cat < ${TEMP_CONFIG_NAME}`
	rm ${TEMP_CONFIG_NAME}
	"${0}" config "${CONFIG_NAME}"
	# if there is another argument, it is likely that it is another key
	# since they seem to get aggregated sometimes - in that case, execute
	# the script again with that as its arg.
	if [ "${2}" != "" ]; then
		"${0}" "${2}" 
	fi
elif [ "${1}" == ${NOTIFY_IP_CHANGE} ]; then
	"${0}" restart
else
	cat <<- echo_end
		Usage:
		  `basename "${0}"` [start | stop | status | restart | lsconfig | config <name>]
		  config files are located in "${SSCF_PATH}" and the <name> should not
		  include the .sscf extension
	echo_end
fi

exit 0