#!/bin/sh
set -e

if jq -e '.["usb-ports"]' /run/system.json > /dev/null; then
    usb_ports=$(jq -r '.["usb-ports"] | map(.name) | unique | join(" ")' /run/system.json)
else
    usb_ports=""
fi
if jq -e '.["wifi-radios"]' /run/system.json > /dev/null 2>&1; then
    wifi_radios=$(jq -r '.["wifi-radios"][].name' /run/system.json)
else
    wifi_radios=""
fi


gen_port()
{
    port="$1"
    cat <<EOF
{
    "class": "infix-hardware:usb",
    "name": "$port",
    "state": {
	"admin-state": "unlocked"
    }
}
EOF
}

gen_radio()
{
    radio="$1"

    # Read band info from system.json (probed at boot by 00-probe)
    phy_info=$(jq -r --arg r "$radio" '.["wifi-radios"][] | select(.name == $r)' /run/system.json 2>/dev/null || echo '{"bands":[]}')
    has_2ghz=$(echo "$phy_info" | jq '[.bands[] | select(.name == "2.4GHz")] | length')
    has_5ghz=$(echo "$phy_info" | jq '[.bands[] | select(.name == "5GHz")] | length')

    # Determine band setting
    # If both bands supported, prefer 5GHz for better performance
    if [ "$has_2ghz" -gt 0 ] && [ "$has_5ghz" -gt 0 ]; then
        band="5GHz"
    elif [ "$has_5ghz" -gt 0 ]; then
        band="5GHz"
    elif [ "$has_2ghz" -gt 0 ]; then
        band="2.4GHz"
    else
        band="2.4GHz"  # Fallback to 2.4GHz for maximum compatibility
    fi

    cat <<EOF
{
    "name": "$radio",
    "class": "infix-hardware:wifi",
    "infix-hardware:wifi-radio": {
        "country-code": "00",
        "band": "$band",
        "channel": "auto"
    }
}
EOF
}

first=1
cat <<EOF
{
  "ietf-hardware:hardware": {
    "component": [
EOF
for port in $usb_ports; do
    if [ $first -eq 0 ]; then
	echo -n ','
    fi
    first=0;
    gen_port "$port"
done
for radio in $wifi_radios; do
    if [ $first -eq 0 ]; then
	echo -n ','
    fi
    first=0;
    gen_radio $radio
done
cat <<EOF
]}
}
EOF
