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

START=30
USE_PROCD=1

EXTRA_COMMANDS="refresh"
EXTRA_HELP="	refresh	Refresh ipsets without new list downloads"

ban_init="/etc/init.d/banip"
ban_script="/usr/bin/banip.sh"
ban_pidfile="/var/run/banip.pid"

if [ -s "${ban_pidfile}" ] && { [ "${action}" = "start" ] || [ "${action}" = "stop" ] || \
	[ "${action}" = "restart" ] || [ "${action}" = "reload" ] || [ "${action}" = "refresh" ]; }
then
	exit 0
fi

boot()
{
	[ -s "${ban_pidfile}" ] && > "${ban_pidfile}"
	rc_procd start_service
}

start_service()
{
	if [ "$("${ban_init}" enabled; printf "%u" ${?})" -eq 0 ]
	then
		if [ "${action}" = "boot" ]
		then
			return 0
		fi
		procd_open_instance "banip"
		procd_set_param command "${ban_script}" "${@}"
		procd_set_param pidfile "${ban_pidfile}"
		procd_set_param nice "$(uci_get banip extra ban_nice "0")"
		procd_set_param stdout 1
		procd_set_param stderr 1
		procd_close_instance
	fi
}

refresh()
{
	rc_procd start_service refresh
}

reload_service()
{
	rc_procd start_service reload
}

stop_service()
{
	rc_procd "${ban_script}" stop
}

restart()
{
	rc_procd start_service restart
}

status_service()
{
	local key keylist value
	local rtfile="$(uci_get banip global ban_rtfile "/tmp/ban_runtime.json")"

	json_load_file "${rtfile}" >/dev/null 2>&1
	json_select data >/dev/null 2>&1
	if [ "${?}" -eq 0 ]
	then
		printf "%s\\n" "::: banIP runtime information"
		json_get_keys keylist
		for key in ${keylist}
		do
			json_get_var value "${key}"
			printf "  + %-10s : %s\\n" "${key}" "${value}"
		done
	else
		printf "%s\\n" "::: no banIP runtime information available"
	fi
}

service_triggers()
{
	local trigger trigger_list="$(uci_get banip global ban_trigger)"
	local delay="$(uci_get banip extra ban_triggerdelay "2")"
	local type="$(uci_get banip extra ban_starttype "start")"

	PROCD_RELOAD_DELAY=$((${delay}*1000))

	if [ -z "${trigger_list}" ] && [ -r "/lib/functions/network.sh" ]
	then
		. "/lib/functions/network.sh"
		network_find_wan trigger_list
	fi

	if [ -n "${trigger_list}" ]
	then
		for trigger in ${trigger_list}
		do
			procd_add_interface_trigger "interface.*.up" "${trigger}" "${ban_init}" "${type}"
		done
	else
		procd_add_raw_trigger "interface.*.up" ${PROCD_RELOAD_DELAY} "${ban_init}" "${type}"
	fi
	procd_add_reload_trigger "banip"
}
