#!/bin/bash
# local-setup.sh — machine-specific setup commands for CodexBar companion.
# Gitignored. Copy-paste these to set up or recover on this machine.
#
# Machine: jamess-mac-mini (Tailscale: jamess-mac-mini.tail02a1a0.ts.net)
# User:    jameslopez

set -euo pipefail

PLIST="$HOME/Library/LaunchAgents/com.codexbar.companion.plist"
LABEL="com.codexbar.companion"
GUI="gui/$(id -u)"
REPO="$HOME/projects/CodexBar-ESP32"

# ── 1. Reload companion launchd service ───────────────────────────────────
echo "==> Reloading companion service..."
launchctl bootout "$GUI/$LABEL" 2>/dev/null || true
launchctl load "$PLIST"
launchctl kickstart "$GUI/$LABEL"
sleep 1

# ── 2. Verify it's healthy ────────────────────────────────────────────────
echo "==> Health check..."
curl -sf http://127.0.0.1:7842/health && echo " OK" || echo " FAILED — check: tail -50 /tmp/codexbar-companion.log"

echo "==> Status..."
curl -sf http://127.0.0.1:7842/status | python3 -m json.tool --no-ensure-ascii 2>/dev/null || curl -sf http://127.0.0.1:7842/status

echo ""
echo "==> ntfy topic:  codingAgentWaitingOnYou"
echo "==> SSH button:  ssh://jameslopez@jamess-mac-mini.tail02a1a0.ts.net"

# ── 3. Start or attach to a persistent tmux session for agent work ────────
# Run this block manually as needed (not in the script, so it doesn't hijack
# your terminal during setup). Copy-paste:
#
#   tmux new-session -A -s agents
#
# -A: attach if session already exists, otherwise create it.
# Name "agents" is just a convention — use whatever makes sense.
#
# From iPhone (Termius/Blink via Tailscale):
#   ssh jameslopez@jamess-mac-mini.tail02a1a0.ts.net
#   tmux attach -t agents      # re-attach to running session
#   tmux ls                    # list sessions

echo ""
echo "==> To start/attach to a persistent tmux session:"
echo "    tmux new-session -A -s agents"
echo ""
echo "Done."
