#!/usr/bin/env bash
# =============================================================================
# Timmy node — graceful stop
# =============================================================================
set -euo pipefail

LAUNCHD_DIR="$HOME/Library/LaunchAgents"
LNCLI="/opt/homebrew/bin/lncli"
LND_DIR="$HOME/.lnd"

RED='\033[0;31m'; GREEN='\033[0;32m'; CYAN='\033[0;36m'; NC='\033[0m'
info() { echo -e "${CYAN}[stop]${NC} $*"; }
ok()   { echo -e "${GREEN}[ok]${NC} $*"; }

# Stop bore tunnel first (fastest)
if BORE_PID=$(pgrep -f "bore local.*5000" 2>/dev/null); then
  info "Stopping bore tunnel (PID $BORE_PID)…"
  kill "$BORE_PID" 2>/dev/null && ok "bore tunnel stopped." || true
fi

# Stop LNbits
info "Stopping LNbits…"
launchctl unload "$LAUNCHD_DIR/com.timmy.lnbits.plist" 2>/dev/null && ok "LNbits stopped." || true
pkill -f "lnbits" 2>/dev/null || true

# Stop LND gracefully via lncli
info "Stopping LND (graceful)…"
"$LNCLI" --lnddir="$LND_DIR" stop 2>/dev/null && ok "LND stop signal sent." || true
sleep 3
launchctl unload "$LAUNCHD_DIR/com.timmy.lnd.plist" 2>/dev/null || true

# Stop Bitcoin Core gracefully via RPC
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SECRETS_FILE="$SCRIPT_DIR/.node-secrets"
[[ -f "$SECRETS_FILE" ]] && source "$SECRETS_FILE"
BTC_ARGS=()
[[ -n "${RPC_USER:-}" ]] && BTC_ARGS+=(-rpcuser="$RPC_USER" -rpcpassword="$RPC_PASS")

info "Stopping Bitcoin Core (graceful — may take 30-60s)…"
/opt/homebrew/bin/bitcoin-cli "${BTC_ARGS[@]}" stop 2>/dev/null && ok "Shutdown signal sent to bitcoind." || true
launchctl unload "$LAUNCHD_DIR/com.timmy.bitcoind.plist" 2>/dev/null || true

echo ""
ok "All services stopped. Data is safe."
