#!/usr/bin/env bash
# Fly.io — WI Node app helper (app lives outside this WordPress repo).
# Prereq: brew install flyctl && fly auth login  (or FLY_API_TOKEN in env)
# Default app name matches .env.dummy.local; override: FLY_WI_NODE_APP=my-app fly-wi-node.sh status

set -euo pipefail
APP="${FLY_WI_NODE_APP:-nodejs-small-wildflower-8030}"

NODE_REPO="${WI_NODE_REPO:-$HOME/Documents/wp-leads-plugins-nodejs}"

usage() {
  echo "Usage: $(basename "$0") logs|status|ssh|deploy|run|wake|wake-all|dashboard|health|open [-- extra fly args]"
  echo "  App: $APP  (override with FLY_WI_NODE_APP)"
  echo "  deploy: fly deploy from sister repo (default: $NODE_REPO)"
  echo "  wake: start one machine (FLY_WI_NODE_MACHINE_ID, default 7849d0da2d32d8)"
  echo "  wake-all: start both FRA machines (7849… + d896…)"
  echo "  run:  remote shell snippet — e.g. run \"ls -la /app\""
  exit 1
}

[[ "${1:-}" ]] || usage
cmd="$1"
shift || true

case "$cmd" in
  logs)    exec fly logs -a "$APP" "$@" ;;
  status)  exec fly status -a "$APP" "$@" ;;
  ssh)     exec fly ssh console -a "$APP" "$@" ;;
  deploy)
    [[ -d "$NODE_REPO" ]] || { echo "deploy: repo not found: $NODE_REPO (set WI_NODE_REPO)"; exit 1; }
    [[ -f "$NODE_REPO/fly.toml" ]] || { echo "deploy: no fly.toml in $NODE_REPO"; exit 1; }
    echo "==> fly deploy -a $APP (cwd: $NODE_REPO)"
    ( cd "$NODE_REPO" && exec fly deploy -a "$APP" "$@" )
    ;;
  run)
    snippet="${*:-}"
    [[ "$snippet" ]] || { echo "run: missing command, e.g. $(basename "$0") run \"ls /app\""; exit 1; }
    exec fly ssh console -a "$APP" --pty=false -C "sh -c $(printf '%q' "$snippet")"
    ;;
  wake)
    mid="${FLY_WI_NODE_MACHINE_ID:-7849d0da2d32d8}"
    exec fly machine start "$mid" -a "$APP" "$@"
    ;;
  wake-all)
    # Both FRA machines (see Fly dashboard → Machines); use under load / before tests needing 2 instances.
    fly machine start 7849d0da2d32d8 -a "$APP" "$@" && fly machine start d89600eb6420d8 -a "$APP" "$@"
    ;;
  dashboard|open) exec open "https://fly.io/apps/${APP}" ;;
  health)  exec curl -sS -o /dev/null -w '%{http_code}\n' --connect-timeout 10 "https://${APP}.fly.dev/" ;;
  *)       usage ;;
esac
