#!/usr/bin/env bash
# Genmon network applet — PNG icon + SSID label + hover details
# Referred to as nm-applet

NEXUS_ROOT="$(cd "$(dirname "$(realpath "$0")")/../.." && pwd)"
ICON_DIR="$NEXUS_ROOT/assets/panel-icons"

signal_icon() {
    local sig=$1
    if   [ "$sig" -ge 80 ]; then echo "${ICON_DIR}/network-wireless-signal-excellent.png"
    elif [ "$sig" -ge 60 ]; then echo "${ICON_DIR}/network-wireless-signal-good.png"
    elif [ "$sig" -ge 40 ]; then echo "${ICON_DIR}/network-wireless-signal-ok.png"
    elif [ "$sig" -ge 20 ]; then echo "${ICON_DIR}/network-wireless-signal-weak.png"
    else                         echo "${ICON_DIR}/network-wireless-signal-none.png"
    fi
}

# Determine the active uplink from the default route rather than NetworkManager's
# connected state: the wired interface (t2_ncm) is unmanaged by NM and never
# reports STATE=connected, so it would otherwise fall through to "offline".
PRIMARY_IF=$(ip route show default 2>/dev/null | awk '/^default/{print $5; exit}')
if [ -n "$PRIMARY_IF" ] && [ -d "/sys/class/net/$PRIMARY_IF/wireless" ]; then
    ACTIVE_TYPE=wifi
elif [ -n "$PRIMARY_IF" ]; then
    ACTIVE_TYPE=ethernet
else
    ACTIVE_TYPE=
fi
POPUP_OPEN=false
[ -f /tmp/nexus-network-popup-visible ] && POPUP_OPEN=true

if [[ "$ACTIVE_TYPE" == "wifi" ]]; then
    IFS=: read -r _ SSID SIGNAL < <(nmcli -t --escape no -f ACTIVE,SSID,SIGNAL dev wifi list --rescan no | grep '^yes')
    IP=$(nmcli -t --escape no -f IP4.ADDRESS dev show | grep -m1 'IP4.ADDRESS' | cut -d: -f2 | cut -d/ -f1)

    echo "<img>$(signal_icon "${SIGNAL:-0}")</img>"
    if $POPUP_OPEN; then
        echo "<tool></tool>"
    else
        echo "<tool>Wireless
SSID:    ${SSID}
Signal:  ${SIGNAL}%
IP:      ${IP:-unknown}</tool>"
    fi
    echo "<click>$HOME/.local/bin/network-popup.py</click>"

elif [[ "$ACTIVE_TYPE" == "ethernet" ]]; then
    # t2_ncm is unmanaged, so read the IP straight off the primary interface.
    IP=$(ip -4 -o addr show "$PRIMARY_IF" 2>/dev/null | awk '{print $4}' | cut -d/ -f1 | head -n1)

    echo "<img>${ICON_DIR}/network-wired.png</img>"
    if $POPUP_OPEN; then
        echo "<tool></tool>"
    else
        echo "<tool>Wired (Ethernet)
Interface: ${PRIMARY_IF:-unknown}
IP:        ${IP:-unknown}</tool>"
    fi
    echo "<click>$HOME/.local/bin/network-popup.py</click>"

else
    echo "<img>${ICON_DIR}/network-offline.png</img>"
    if $POPUP_OPEN; then
        echo "<tool></tool>"
    else
        echo "<tool>No active network connection</tool>"
    fi
    echo "<click>$HOME/.local/bin/network-popup.py</click>"
fi
