#!/bin/sh /etc/rc.common
# Copyright (c) 2021 OpenWrt.org

START=40

USE_PROCD=1
PROG=/usr/sbin/udhcpsnoop

add_option() {
	local type="$1"
	local name="$2"
	local default="$3"

	config_get val "$cfg" "$name"

	[ -n "$val" ] && json_add_$type "$name" "${val:-$default}"
}

add_device() {
	local cfg="$1"

	config_get_bool disabled "$cfg" disabled 0
	[ "$disabled" -gt 0 ] && return

	config_get name "$cfg" name
	json_add_object "$name"

	add_option boolean ingress 1
	add_option boolean egress 1

	json_close_object
}

reload_service() {
	json_init

	config_load dhcpsnoop

	json_add_object devices
	config_foreach add_device device 
	json_close_object

	ubus call dhcpsnoop config "$(json_dump)"
}

service_triggers() {
	procd_add_reload_trigger dhcpsnoop
}

start_service() {
	procd_open_instance
	procd_set_param command "$PROG"
	procd_set_param respawn
	procd_close_instance
}

service_started() {
	ubus -t 10 wait_for dhcpsnoop
	[ $? = 0 ] && reload_service
}
