#!/bin/sh
# hexnet-routes.sh
# Exports IPv4 routes (with gateway) to hexnet_routes.json
# for import into the HexNet DHCP option 121 converter.
#
# Usage:
#   sh hexnet-routes.sh [output-file]
#
# No dependencies beyond coreutils: uses 'ip' (iproute2) when available,
# falls back to 'route -n' (net-tools). Works on any mainstream Linux.

OUT="${1:-hexnet_routes.json}"
TMP="/tmp/hexnet_routes_norm.$$"
LINES="/tmp/hexnet_routes_lines.$$"
MAINFILE="/tmp/hexnet_routes_main.$$"
trap 'rm -f "$TMP" "$LINES" "$MAINFILE"' EXIT HUP INT TERM

# Normalize "ip route show": prints "metric<TAB>target<TAB>gw"
norm_ip() {
    awk '{
        if (NF < 3 || $2 != "via") next
        target = $1
        gw = $3
        metric = 0
        for (i = 3; i <= NF; i++) {
            if ($i == "metric") { metric = $(i + 1); break }
        }
        if (gw == "0.0.0.0") next
        if (target == "default") target = "0.0.0.0/0"
        print metric "\t" target "\t" gw
    }'
}

# Normalize "route -n": prints "metric<TAB>target<TAB>gw"
norm_route() {
    awk '{
        if (NF < 8) next
        if ($4 !~ /G/) next
        if ($2 == "*" || $2 == "0.0.0.0") next
        dest = $1
        mask = $3
        gw = $2
        metric = $5
        ones = 0
        split(mask, m, ".")
        for (i = 1; i <= 4; i++) {
            v = m[i] + 0
            while (v >= 128) { ones++; v = (v - 128) * 2 }
        }
        if (dest == "0.0.0.0" && mask == "0.0.0.0") dest = "0.0.0.0/0"
        else dest = dest "/" ones
        print metric "\t" dest "\t" gw
    }'
}

if command -v ip >/dev/null 2>&1; then
    ip route show | norm_ip > "$TMP"
elif command -v route >/dev/null 2>&1; then
    route -n | norm_route > "$TMP"
else
    echo "ERROR: neither 'ip' (iproute2) nor 'route' (net-tools) found" >&2
    exit 1
fi

: > "$MAINFILE"
sort -n -t"$(printf '\t')" -k1,1 "$TMP" | while IFS="$(printf '\t')" read -r metric target gw; do
    [ -z "$target" ] && continue
    if [ "$target" = "0.0.0.0/0" ]; then
        echo "$gw" > "$MAINFILE"
        continue
    fi
    printf '{"target":"%s","router":"%s"}\n' "$target" "$gw"
done > "$LINES"

MAIN="$(cat "$MAINFILE" 2>/dev/null)"
{
    printf '{"main_router":"%s","rows":[' "$MAIN"
    first=1
    while IFS= read -r line; do
        if [ "$first" -eq 1 ]; then first=0; else printf ','; fi
        printf '%s' "$line"
    done < "$LINES"
    printf ']}\n'
} > "$OUT"

echo "Routes saved to: $OUT"
cat "$OUT"