#!/bin/sh /etc/rc.common
# Copyright (C) 2006 OpenWrt.org

START=50
USE_PROCD=1

validate_qos_section()
{
	uci_validate_section qos interface "${1}" \
		'enabled:bool' \
		'upload:uinteger' \
		'download:uinteger'
}

service_triggers()
{
	procd_add_reload_trigger "qos"
	procd_add_validation validate_qos_section
	qos-start
}

# True when at least one qos interface section is enabled, i.e. when there is
# any shaping to install.
qos_any_enabled() {
	local enabled_found=0
	config_load qos
	config_foreach _qos_check_enabled interface
	[ "$enabled_found" = 1 ]
}

_qos_check_enabled() {
	local enabled
	config_get_bool enabled "$1" enabled 0
	[ "$enabled" = 1 ] && enabled_found=1
	return 0
}

boot() {
	# qos-start is `qos-stop` followed by `generate.sh all | sh`, i.e. a full
	# teardown and rebuild. On a fresh boot there is nothing to tear down, and
	# if no interface has enabled=1 there is nothing to build either -- yet it
	# still cost 1.254s of every boot here, measured with /etc/rc.d/S* wrapped
	# in kmsg timestamps. procd's rcS is strictly serial (rcS.c:
	# q.max_running_tasks = 1), so that delayed every service behind S50.
	#
	# Only the boot path is skipped. start/reload still run unconditionally, so
	# turning QoS off and reloading still tears the existing rules down.
	if qos_any_enabled; then
		qos-start
	fi
}

start_service() {
	qos-start
}

reload_service() {
	qos-start
}
