#!/bin/bash
# The People's Tips - results poller installer (macOS)
# Installs to ~/tips-poller and schedules it every 15 minutes via launchd.
# Re-running this is safe: it overwrites and reloads cleanly.

set -e

DIR="$HOME/tips-poller"
PLIST="$HOME/Library/LaunchAgents/com.peoplestips.poller.plist"
LABEL="com.peoplestips.poller"
BASE="https://the-peoples-tips.netlify.app/setup"

echo ""
echo "  The People's Tips - results poller"
echo "  =================================="
echo ""

# --- 1. python3 present? -------------------------------------------------
if ! command -v python3 >/dev/null 2>&1; then
  echo "  python3 isn't installed. macOS will offer to install it now."
  echo "  Accept the prompt, wait for it to finish, then run this again."
  xcode-select --install 2>/dev/null || true
  exit 1
fi
PY="$(command -v python3)"
echo "  python3 ....... $($PY --version 2>&1)  [$PY]"

# --- 2. fetch the poller -------------------------------------------------
mkdir -p "$DIR"
echo "  downloading ... $DIR/tips-poller.py"
curl -fsSL "$BASE/tips-poller.py" -o "$DIR/tips-poller.py"
chmod +x "$DIR/tips-poller.py"

# --- 3. connectivity check ----------------------------------------------
echo ""
echo "  checking connections..."
echo ""
if ! "$PY" "$DIR/tips-poller.py" --check; then
  echo ""
  echo "  Something above failed. Nothing has been scheduled."
  echo "  If the feed is blocked, this machine is likely on a VPN."
  echo "  Turn the VPN off and run this again."
  exit 1
fi

# --- 4. schedule it -----------------------------------------------------
mkdir -p "$HOME/Library/LaunchAgents"
cat > "$PLIST" <<PLISTEOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key><string>$LABEL</string>
  <key>ProgramArguments</key>
  <array>
    <string>$PY</string>
    <string>$DIR/tips-poller.py</string>
  </array>
  <key>StartInterval</key><integer>900</integer>
  <key>RunAtLoad</key><true/>
  <key>StandardOutPath</key><string>$DIR/poller.log</string>
  <key>StandardErrorPath</key><string>$DIR/poller.log</string>
  <key>ProcessType</key><string>Background</string>
</dict>
</plist>
PLISTEOF

launchctl bootout "gui/$(id -u)/$LABEL" 2>/dev/null || true
launchctl bootstrap "gui/$(id -u)" "$PLIST"

echo ""
echo "  Scheduled. Runs every 15 minutes, starting now."
echo ""
echo "  Watch it:     tail -f $DIR/poller.log"
echo "  Backfill:     $PY $DIR/tips-poller.py 2026-08-29"
echo "  Stop it:      launchctl bootout gui/$(id -u)/$LABEL"
echo "  Start again:  launchctl bootstrap gui/$(id -u) $PLIST"
echo ""
echo "  Results appear at https://the-peoples-tips.netlify.app  ->  Results tab"
echo ""
