#!/bin/sh
. /lib/functions.sh

LUCI_RELOAD_LOGFILE="/tmp/luci.log"
LUCI_RELOAD_DEBUG=0

reload_debug() {
	[ "$LUCI_RELOAD_DEBUG" -eq 1 ] && echo "$@" >>$LUCI_RELOAD_LOGFILE
}

apply_config() {
	config_get init "$1" init
	config_get exec "$1" exec
	config_get test "$1" test

	echo "$2" > "/var/run/luci-reload-status"

	[ -n "$init" ] && reload_init "$2" "$init" "$test"
	[ -n "$exec" ] && reload_exec "$2" "$exec" "$test"
}

reload_exec() {
	local service="$1"
	local cmd="$2"
	local ok="$3"
	
	[ -x "$cmd" ] && {
		echo "Reloading $service... "
		reload_debug "    reload_exec: execute \"$cmd\""
		$cmd >/dev/null 2>&1
		[ -n "$ok" -a "$?" != "$ok" ] && echo '!!! Failed to reload' $service '!!!'
	}
}

reload_init() {
	/bin/systemctl is-enabled $2 >/dev/null 2>&1 && {
		echo "Reloading $1... "
		reload_debug "    reload_init: restart $1"
		/bin/systemctl reload $2 >/dev/null 2>&1 || /bin/systemctl restart $2 >/dev/null 2>&1
		[ -n "$3" -a "$?" != "$3" ] && echo '!!! Failed to reload' $1 '!!!'
	}
}

lock "/var/run/luci-reload"

config_load ucitrack

# Remove wireless if need to restart netifd(idp-2.x: network)
all_servers="$*"
if echo "${all_servers}" | grep -q "netifd" ; then
	all_servers=$(echo ${all_servers} | sed 's/wireless//g')
fi
reload_debug "==== [$(date)] luci_reload: ${all_servers}"

for i in ${all_servers}; do
	config_foreach apply_config $i $i
done

rm -f "/var/run/luci-reload-status"
lock -u "/var/run/luci-reload"
