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

redundant_values=$(printf "system/maintenance/eventlog/%s* " general system network connections)
allowed_path="system/maintenance/eventlog/all*"
CONFIG="rpcd"

check_targets() {
	local section="$1"
	local option="$2"
	local target="$3"
	local values=$(uci_get "$CONFIG" "$section" "$option")

	[ "$target" = "deny" ] || return
	# check if all deny values are deleted and change to allow
	[ "$values" = "!superuser *" ] && uci_set "$CONFIG" "$section" "target_$option" 
}

modify_paths() {
	local section="$1"
	local option="$2"
	local value="$3"
	local target="$4"
	local config_values=$(uci_get "$CONFIG.$section.$option")
	echo "$config_values" | grep -q "$value" || return
	uci_remove_list "$CONFIG" "$section" "$option" "$value"
	uci_remove_list "$CONFIG" "$section" "$option" "!$value"
	check_targets "$section" "$option" "$target"

	[ "$target" = "allow" ] && ! echo "$config_values" | grep -q "$allowed_path" && uci_add_list "$CONFIG" "$section" "$option" "$allowed_path"
}

check_config_match() {
	local section="$1"
	local target_write=$(uci_get "$CONFIG.$section.target_write" 2>/dev/null)
	local target_read=$(uci_get "$CONFIG.$section.target_read" 2>/dev/null)

	for value in $redundant_values; do
		modify_paths $section "read" $value $target_read
		modify_paths $section "write" $value $target_write
	done
}

config_load "$CONFIG"
sed -i "s/system\/maintenance\/eventlog\*'/system\/maintenance\/eventlog\/all\*'/g" "$UCI_CONFIG_DIR/rpcd"
config_foreach check_config_match "group"
uci_commit "$CONFIG"
exit 0
