#!/usr/bin/env bash
# hotspot-keepalive.sh — Auto-reconnect to Alfred hotspot
# Checks every 30s, reconnects if dropped.

SSID="Alfred"
IFACE="en0"
LOG="$HOME/.hermes/logs/hotspot.log"
CHECK_INTERVAL=30

log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] HOTSPOT: $*" >> "$LOG"; }

log "=== Keepalive started for SSID: $SSID ==="

while true; do
  current=$(networksetup -getairportnetwork "$IFACE" 2>/dev/null | sed 's/.*: //')

  if [ "$current" = "$SSID" ]; then
    # Connected — check we actually have internet
    if ! ping -c 1 -W 3 8.8.8.8 >/dev/null 2>&1; then
      log "Connected to $SSID but no internet — forcing reconnect"
      networksetup -setairportnetwork "$IFACE" "$SSID" 2>/dev/null
    fi
  else
    log "Not on $SSID (current: ${current:-none}) — reconnecting..."
    networksetup -setairportnetwork "$IFACE" "$SSID" 2>/dev/null
    sleep 5
    new=$(networksetup -getairportnetwork "$IFACE" 2>/dev/null | sed 's/.*: //')
    if [ "$new" = "$SSID" ]; then
      log "Reconnected to $SSID"
    else
      log "FAILED to reconnect (got: ${new:-none}) — retrying in ${CHECK_INTERVAL}s"
    fi
  fi

  sleep "$CHECK_INTERVAL"
done
