#!/bin/bash

# Status bar module for Surge download manager
# Shows daemon status on stargate (via tailscale) and active download count
# Left click opens surge TUI connected to stargate

SURGE_HOST="100.74.152.79"
SURGE_PORT="1700"
SURGE_TOKEN="34b6f205-2ed9-4131-8cd7-cc27b0f1b39e"
SURGE_ADDR="$SURGE_HOST:$SURGE_PORT"

case $BLOCK_BUTTON in
	1) setsid -f "$TERMINAL" -e surge connect "http://$SURGE_ADDR" --token "$SURGE_TOKEN" --insecure-http ;;
	3) notify-send "󰇚 Surge module" "Surge download manager on stargate
- Left click: open Surge TUI
- Server: $SURGE_ADDR (tailscale)
- Downloads: /mnt/storage/downloads" ;;
	6) setsid -f "$TERMINAL" -e "$EDITOR" "$0" ;;
esac

# Quick API check — get download list from stargate
response=$(curl -sf -m 2 -H "Authorization: Bearer $SURGE_TOKEN" "http://$SURGE_ADDR/list" 2>/dev/null)

if [ $? -ne 0 ]; then
	printf "󰇚 off\n"
	exit 0
fi

# Count active downloads (status "downloading" in JSON array)
# Handle null/empty response (no downloads)
if [ "$response" = "null" ] || [ -z "$response" ]; then
	printf "󰇚\n"
	exit 0
fi

active=$(printf '%s' "$response" | grep -oc '"status":"downloading"' 2>/dev/null || echo 0)

if [ "$active" -gt 0 ]; then
	printf "󰇚 %s\n" "${active}dl"
else
	printf "󰇚\n"
fi
