#!/bin/sh
#
# PROVIDE: configd
# REQUIRE: SERVERS
# KEYWORD: shutdown
#

. /etc/rc.subr

name="configd"
rcvar="configd_enable"
: ${configd_enable="YES"}
pidfile="/var/run/${name}.pid"
sockfile="/var/run/configd.socket"

start_precmd=configd_prestart
start_postcmd=configd_poststart
stop_cmd=configd_stop
stop_postcmd=configd_poststop

configd_load_rc_config()
{
	required_args=""
	required_dirs="/usr/local/opnsense/service/"
	required_files=""
	command_args="${required_args}"
	command=/usr/local/opnsense/service/configd.py
	command_interpreter=/usr/local/bin/python3
}

configd_prestart()
{
	# clean up again just in case as poststart will probe for socket
	configd_poststop

	# reset access rights on configd daemon script
	chmod 700 /usr/local/opnsense/service/configd.py
}

configd_poststart()
{
	# give the daemon some time to initialize its configuration
	for i in 1 2 3 4 5; do
		sleep 1

		if [ -S ${sockfile} ]; then
			break
		fi
	done
}

# kill configd
configd_stop()
{
	if [ -z "$rc_pid" ]; then
		[ -n "$rc_fast" ] && return 0
		_run_rc_notrunning
		return 1
	fi

	echo -n "Stopping ${name}."
	# first ask gently to exit
	kill -15 ${rc_pid}

	# wait max 2 seconds for gentle exit
	for i in $(seq 1 20);
	do
		if [ -z "`/bin/ps -ex | /usr/bin/awk '{print $1;}' | /usr/bin/grep "^${rc_pid}"`" ]; then
			break
		fi
		sleep 0.1
	done

	# kill any remaining configd processes (if still running)
	for configd_pid in `/bin/ps -ex | grep 'configd.py' | /usr/bin/awk '{print $1;}' `
	do
	   kill -9 $configd_pid >/dev/null 2>&1
	done

	echo  "..done"
}

# cleanup after stopping configd
configd_poststop()
{
	rm -f ${sockfile}
}

load_rc_config $name
configd_load_rc_config
run_rc_command $1
