#!/usr/bin/env bash
# Genmon Nexus applet — logo icon whose state tracks the running services,
# left-click opens the control popup. Mirrors network-applet.sh.

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

# Fast, dependency-free liveness check via bash's built-in /dev/tcp — no curl
# round-trip on every 5s genmon tick.
port_up() {
    (exec 3<>"/dev/tcp/127.0.0.1/$1") 2>/dev/null && { exec 3>&- 3<&-; return 0; }
    return 1
}

state() { port_up "$1" && echo "up" || echo "down"; }

BACKEND=$(state 8000)   # Synapse
MEMORY=$(state 8001)    # Memory service
FRONTEND=$(state 5173)  # Vite frontend

up=0
[ "$BACKEND"  = up ] && up=$((up + 1))
[ "$MEMORY"   = up ] && up=$((up + 1))
[ "$FRONTEND" = up ] && up=$((up + 1))

if   [ "$up" -eq 3 ]; then ICON="$ICON_DIR/nexus-on.png"
elif [ "$up" -eq 0 ]; then ICON="$ICON_DIR/nexus-off.png"
else                       ICON="$ICON_DIR/nexus-partial.png"
fi

dot() { [ "$1" = up ] && echo "●" || echo "○"; }

echo "<img>$ICON</img>"
echo "<tool>NexusOS  —  ${up}/3 services up
$(dot "$BACKEND")  Synapse backend   :8000
$(dot "$MEMORY")  Memory service      :8001
$(dot "$FRONTEND")  Frontend (Vite)       :5173</tool>"
echo "<click>$HOME/.local/bin/nexus-popup.py</click>"
