#!/sbin/openrc-run
MOSQUITTO_CFG="${MOSQUITTO_CFG:-/etc/mosquitto/${RC_SVCNAME}.conf}"

command="/usr/bin/mosquitto"
command_args="-c '${MOSQUITTO_CFG}' $command_args"
command_args_background="--daemon"
pidfile="$(awk '$1 == "pid_file" {print $2}' "${MOSQUITTO_CFG}" || true)"

extra_started_commands="reload"
description_reload="Reload configuration"

start_pre() {
	if ! [ -e "$MOSQUITTO_CFG" ]; then
		eerror "$MOSQUITTO_CFG does not exist"
		return 1
	fi

	if [ -z "$pidfile" ]; then
		eerror "${MOSQUITTO_CFG} is missing the pid_file option"
		return 1
	fi

	MOSQUITTO_LOG="$(awk '$1 " " $2 == "log_dest file" {print $3}' "${MOSQUITTO_CFG}")"
	if [ -n "$MOSQUITTO_LOG" ]; then
		MOSQUITTO_USER="$(awk '$1 == "user" {print $2}' "${MOSQUITTO_CFG}")"
		MOSQUITTO_USER="${MOSQUITTO_USER:-mosquitto}"
		checkpath -fm 660 -o "${MOSQUITTO_USER}" \
			"${MOSQUITTO_LOG}" || return 1
	fi
}

reload() {
	ebegin "Reloading ${RC_SVCNAME}"
	start-stop-daemon --signal HUP --pidfile "${pidfile}"
	eend $?
}