#!/usr/bin/env bash
# Graceful fixture stop on one Pi: kill bridge/listen workers, then rclone upload.
#
# Usage (on Pi or via SSH from PC orchestrator):
#   cd ~/EtherGold/dev
#   bash stop_fixture_session.sh
#   SYNC_ONLY=1 bash stop_fixture_session.sh   # skip pkill, upload only

if grep -q $'\r' "${BASH_SOURCE[0]}" 2>/dev/null; then
  sed -i 's/\r$//' "${BASH_SOURCE[0]}"
  exec bash "${BASH_SOURCE[0]}" "$@"
fi

set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
for _sync in \
  "${ETHERGOLD_SYNC:-}" \
  "${ROOT}/../sync" \
  "/home/topbox/EtherGold/sync"; do
  if [[ -f "${_sync}/ethergold_paths.sh" ]]; then
    # shellcheck source=/dev/null
    source "${_sync}/ethergold_paths.sh"
    break
  fi
done
unset _sync
SYNC="${ETHERGOLD_SYNC:-${ROOT}/../sync}"
STAMP_FILE="${SYNC}/.session_upload_complete"
LOG="${ROOT}/logs/orchestrator.log"
SYNC_LOG="${ROOT}/logs/.sync_last.log"

mkdir -p "${ROOT}/logs"

log() {
  printf '%s %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*" >> "${LOG}"
}

# Fresh stop journal — full rclone transcript goes to .sync_last.log only.
: > "${LOG}"

stop_workers() {
  local sig="${1:-TERM}"
  local pattern name
  for pattern in fixture_supervisor fixture_link_watch pog422_uartd pog422_fixture_bridge pog422_listen.py pog422_fixture_listen hat_listen.sh; do
    if pgrep -f "${pattern}" >/dev/null 2>&1; then
      log "stop: pkill -${sig} -f ${pattern}"
      pkill "-${sig}" -f "${pattern}" || true
    fi
  done
}

if [[ "${SYNC_ONLY:-0}" != "1" ]]; then
  log "=== stop_fixture_session ==="
  if systemctl is-active --quiet ethergold-collector.service 2>/dev/null; then
    echo "WARN: ethergold-collector.service is active (holds Pi HS BCM9)." >&2
    echo "  pkill of pog422_listen.py will come back in RestartSec." >&2
    echo "  Workshop listen: sudo systemctl stop ethergold-collector.service" >&2
    log "WARN: ethergold-collector.service active — pkill is not enough"
  fi
  stop_workers TERM
  sleep 1
  if pgrep -f 'pog422_uartd|pog422_fixture_bridge|pog422_listen.py|pog422_fixture_listen|hat_listen.sh|fixture_link_watch' >/dev/null 2>&1; then
    stop_workers KILL
    sleep 0.5
  fi
  rm -f "${ROOT}/.bridge.pid"
fi

if [[ "${SKIP_SYNC:-0}" == "1" ]]; then
  log "skip: sync_to_dropbox (SKIP_SYNC=1)"
  log "=== stop_fixture_session complete (no upload) ==="
  exit 0
fi

if [[ ! -x "${SYNC}/sync_to_dropbox.sh" && ! -f "${SYNC}/sync_to_dropbox.sh" ]]; then
  log "ERROR: missing ${SYNC}/sync_to_dropbox.sh"
  exit 1
fi

: > "${SYNC_LOG}"

# Drain already-rotated siblings before live capture sync (keeps stop upload small).
# Prefer fixture-/dev worker; fall back to legacy generic offload.
if [[ -f "${SYNC}/offload_fixture_dev_rotated.sh" ]]; then
  log "pre-offload: offload_fixture_dev_rotated.sh"
  if ! bash "${SYNC}/offload_fixture_dev_rotated.sh" >> "${SYNC_LOG}" 2>&1; then
    log "WARN: offload_fixture_dev_rotated failed (continuing with sync_to_dropbox)"
    tail -n 8 "${SYNC_LOG}" >> "${LOG}" 2>/dev/null || true
  fi
elif [[ -f "${SYNC}/offload_rotated_capture.sh" ]]; then
  log "pre-offload: offload_rotated_capture.sh"
  if ! bash "${SYNC}/offload_rotated_capture.sh" >> "${SYNC_LOG}" 2>&1; then
    log "WARN: offload_rotated_capture failed (continuing with sync_to_dropbox)"
    tail -n 8 "${SYNC_LOG}" >> "${LOG}" 2>/dev/null || true
  fi
fi

log "upload: sync_to_dropbox.sh"
if ! bash "${SYNC}/sync_to_dropbox.sh" >> "${SYNC_LOG}" 2>&1; then
  log "ERROR: sync_to_dropbox failed (tail logs/.sync_last.log)"
  tail -n 15 "${SYNC_LOG}" >> "${LOG}" 2>/dev/null || true
  exit 1
fi
tail -n 3 "${SYNC_LOG}" >> "${LOG}" 2>/dev/null || true

date -u +%Y-%m-%dT%H:%M:%SZ > "${STAMP_FILE}"
log "done: wrote ${STAMP_FILE}"
log "=== stop_fixture_session complete ==="
