#!/bin/sh /etc/rc.common

# Copyright 2020, 2023 eomanis
#
# This file is part of yabddnsd.
#
# yabddnsd is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# yabddnsd is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with yabddnsd.  If not, see <http://www.gnu.org/licenses/>.

# shellcheck disable=SC2034  # Unused variables
START=99
# shellcheck disable=SC2034  # Unused variables
USE_PROCD=1

NAME='yabddnsd'
PROG='/usr/bin/yabddnsd'
INSTANCES_ROOT='/etc/yabddnsd/instances'

# Spawns a "yabddnsd --config-file config-file.conf" service instance
# for every *.conf file in $INSTANCES_ROOT
start_service () {
	local instancesFound=false
	local configFile
	local configFileName
	local IFS=$'\n' # This DOES work with busybox's ash
	local oldState

	oldState="$(set +o)" # Store current shell options
	set -f # Disable path globbing
	if test -d "$INSTANCES_ROOT"; then
		# shellcheck disable=SC2044  # This, with a custom IFS and with
		# "set -f", seems to be the cleanest solution when process
		# substitution is not available
		for configFile in $(find "$INSTANCES_ROOT" -mindepth 1 -maxdepth 1 -type f -name "*.conf" -print | sort); do
			instancesFound=true
			configFileName="$(basename "$configFile")"

			# Let's hope all of this still works as advertised with
			# "set -f" and the custom IFS
			echo " INFO  Starting instance \"$configFileName\" for configuration file \"$configFile\"" >&2
			procd_open_instance "$configFileName"
			procd_set_param command "$PROG" --config-file "$configFile"
			procd_set_param respawn "${respawn_threshold:-900}" "${respawn_timeout:-5}" "${respawn_retry:-5}"
			procd_set_param stdout 1
			procd_set_param stderr 1
			procd_close_instance
		done
	fi
	set +vx; eval "$oldState" # Restore previous shell options
	if ! $instancesFound; then
		echo " WARN  No ${INSTANCES_ROOT}/*.conf files found, not doing anything" >&2
	fi
}

# Uncomment as soon as yabddnsd implements handling SIGHUP
#service_triggers () {
#
#	# Watch all network devices
#	# TODO Does not appear to be effective with * as network device name
#	procd_add_interface_trigger "interface.*" '*' "/etc/init.d/$NAME"
#}

# Uncomment as soon as yabddnsd implements handling SIGHUP
#reload_service () {
#
#	procd_send_signal "$NAME"
#}