#!/bin/sh

. /lib/functions.sh

cfg="mapcontroller"
config_load "$cfg"

used_ids=""

collect_used_ids() {
	local section="$1"
	local id

	id=$(uci -q get ${cfg}.${section}.id)
	if [ -n "$id" ] && printf "%s" "$id" | grep -qE '^[0-9]+$'; then
		used_ids="$used_ids $id"
	fi
}

# Find first available ID from 0 to INT32_MAX
find_first_available_id() {
	local max_int=2147483647
	local expected=0
	local id

	# Convert list to sorted unique list
	sorted_ids=$(printf "%s\n" $used_ids | sort -n | uniq)

	for id in $sorted_ids; do
		if [ "$id" -eq "$expected" ]; then
			expected=$((expected + 1))
		elif [ "$id" -gt "$expected" ]; then
			# Found a gap -> return the gap
			echo "$expected"
			return
		fi
	done

	# If no gaps, next available is `expected`
	if [ "$expected" -le "$max_int" ]; then
		echo "$expected"
	else
		echo -1
	fi
}

# Assign ID if missing
add_qos_rule_id() {
	local section="$1"
	local id

	id=$(uci -q get ${cfg}.${section}.id)
	if [ -z "$id" ]; then
		new_id=$(find_first_available_id)
		[ "$new_id" -ge 0 ] || return # No available ID
		uci -q set ${cfg}.${section}.id="$new_id"

		used_ids="$used_ids $new_id"
	fi
}

# Step 1: Collect all existing IDs
config_foreach collect_used_ids qos_rule

# Step 2: Assign IDs to rules missing them
config_foreach add_qos_rule_id qos_rule
