#!/bin/sh

. /usr/share/libubox/jshn.sh

____keys=
____rukeys=

key_append() {
	____keys="${____keys}""${____keys:+ }""$1"
}

key_ctor() {
	i=0
	while [ $i -lt $2 ];do
		____keys="${____keys}""${____keys:+ }""$1$i"
		i=$((i + 1))
	done
}

rukey_ctor() {
	i=0
	while [ $i -lt $2 ];do
		____rukeys="${____rukeys}""${____rukeys:+ }""$1$i"
		i=$((i + 1))
	done
}

key_dispatch() {
	for key in $____keys;do
		json_get_var "$key" "$key"
		[ -n "$(eval echo \$$key)" ] && key_dispatch_cb "$key"
	done
}

rule_dispatch() {
	local __function=$1
	local __rule_fields=$2
	local __rule_name=$3
	local key=0

	json_get_keys arrs "$__rule_fields"
	json_select "$__rule_fields"
	for arr in $arrs; do
		key=0
		json_select "$arr"
		json_get_var idx "${__rule_fields%?}1"
		json_get_var cmd "${__rule_fields%?}2"

		if [ "$cmd" = "2" ];then
			eval $__function "$key" "$__rule_name$idx" "$cmd"
		else
			uci get csdp."$__rule_name$idx" || eval $__function "$key" "$__rule_name$idx" "1"
			for key in $____rukeys;do
				json_get_var "$key" "$key"
				[ -n "$(eval echo \$$key)" ] && eval $__function "$key" "$__rule_name$idx" "$cmd"
			done
		fi
		json_select ..
	done
	[ "$arrs" != "" ] && json_select ..
}