#!/sbin/openrc-run
# Copyright 2017 Steffen Christgau
# Distributed under the terms of the MIT licence

depend() {
	need net
	need samba
}

SMB_CONFIG_FILE="/etc/samba/smb.conf"
LOG_FILE="${WSDD_LOG_FILE:-/var/log/wsdd.log}"
WSDD_EXEC="/usr/bin/wsdd"
RUN_AS_USER="${WSDD_USER:-daemon:daemon}"

start() {
	ebegin "Starting ${RC_SVCNAME} daemon"

	OPTS="${WSDD_OPTS}"

	if [ -z "$WSDD_WORKGROUP" ]; then
		# try to extract workgroup with Samba's testparm
		if which testparm >/dev/null 2>/dev/null; then
			GROUP="$(testparm -s --parameter-name workgroup 2>/dev/null)"
		fi

		# fallback to poor man's approach if testparm is unavailable or failed for some reason
		if [ -z "$GROUP" ] && [ -r "${SMB_CONFIG_FILE}" ]; then
			GROUP=`grep -i '^\s*workgroup\s*=' ${SMB_CONFIG_FILE} | cut -f2 -d= | tr -d '[:blank:]'`
		fi

		if [ -n "${GROUP}" ]; then
			OPTS="-w ${GROUP} ${OPTS}"
		fi
	else
		OPTS="-w ${WSDD_WORKGROUP} ${OPTS}"
	fi

	if [ ! -r "${LOG_FILE}" ]; then
		touch "${LOG_FILE}"
	fi
	chown ${RUN_AS_USER} "${LOG_FILE}"

	start-stop-daemon --start --background --user ${RUN_AS_USER} --make-pidfile --pidfile /var/run/${RC_SVCNAME}.pid --stdout "${LOG_FILE}" --stderr "${LOG_FILE}" --exec ${WSDD_EXEC} -- ${OPTS}
	eend $?
}

stop() {
	ebegin "Stopping ${RC_SVCNAME} daemon"
	start-stop-daemon --stop --retry 2 --pidfile /var/run/${RC_SVCNAME}.pid --exec ${WSDD_EXEC}
	eend $?
}
