#!/usr/bin/env bash
# Networking backend for the astal-menu Network quad.
# Each subcommand prints JSON (or plain text for pubip) to stdout. Wi-Fi listing and
# state come from AstalNetwork in the UI; this covers the rest (ip/routes/ports,
# public IP, wifi connect via nmcli, and the manual/DHCP switch).
set -euo pipefail

active_conn() {
    # First active connection on a real device (wifi/ethernet).
    nmcli -t -g NAME,TYPE,DEVICE connection show --active 2>/dev/null \
        | awk -F: '$2 ~ /wireless|ethernet/ {print $1; exit}'
}

cmd="${1:-}"; shift || true
case "$cmd" in
    ip)
        ip -j addr show 2>/dev/null || echo '[]'
        ;;
    routes)
        ip -j route show 2>/dev/null || echo '[]'
        ;;
    ports)
        # Listening TCP/UDP sockets -> JSON array.
        ss -tulnH 2>/dev/null | awk '
            BEGIN { print "["; sep="" }
            { printf "%s{\"proto\":\"%s\",\"local\":\"%s\"}", sep, $1, $5; sep="," }
            END { print "]" }'
        ;;
    pubip)
        curl -sf --max-time 8 https://ifconfig.co 2>/dev/null \
            || curl -sf --max-time 8 https://api.ipify.org 2>/dev/null \
            || echo "unavailable"
        ;;
    wifi-connect)
        ssid="${1:-}"; pass="${2:-}"
        if [[ -n "$pass" ]]; then
            nmcli dev wifi connect "$ssid" password "$pass"
        else
            nmcli dev wifi connect "$ssid"
        fi
        ;;
    wifi-disconnect)
        con="$(active_conn)"
        [[ -n "$con" ]] && nmcli connection down "$con"
        ;;
    set-manual)
        con="${4:-$(active_conn)}"; addr="${1:-}"; gw="${2:-}"; dns="${3:-}"
        [[ -z "$con" ]] && { echo "no active connection" >&2; exit 1; }
        nmcli connection modify "$con" ipv4.method manual \
            ipv4.addresses "$addr" ipv4.gateway "$gw" ipv4.dns "$dns"
        nmcli connection up "$con"
        ;;
    set-dhcp)
        con="${1:-$(active_conn)}"
        [[ -z "$con" ]] && { echo "no active connection" >&2; exit 1; }
        nmcli connection modify "$con" ipv4.method auto
        nmcli connection up "$con"
        ;;
    active-conn)
        active_conn
        ;;
    *)
        echo "usage: network.sh {ip|routes|ports|pubip|wifi-connect|wifi-disconnect|set-manual|set-dhcp|active-conn}" >&2
        exit 2
        ;;
esac
