#!/usr/bin/env bash
# bubblecam-arm -- run this over the LAST SSH session before sealing the
# enclosure. It runs pre-flight checks, prints a go/no-go summary, asks for
# explicit confirmation, and only then disables the radios (which ends the
# very SSH session it's running in) and stops mDNS.
#
# Deliberately manual, not a timer/automatic trigger -- an automatic
# radio-disable could race the operator's own pre-deployment checkout
# session. NetworkManager (nmcli) is assumed per current Raspberry Pi OS
# Bookworm defaults; rfkill is used alongside it as belt-and-suspenders --
# confirm which network stack is actually active on your image before
# relying on this unattended.

set -uo pipefail

STATE_DIR="${BUBBLECAM_STATE_DIR:-/run/bubblecam}"
BUBBLECAM_LIB="${BUBBLECAM_LIB:-/opt/bubblecam}"
DATA_DIR="${BUBBLECAM_DATA_DIR:-/data}"
MIN_FREE_GB="${BUBBLECAM_MIN_FREE_GB:-20}"

fail=0

echo "=== BubbleCam pre-seal check ==="
echo "-- service state --"

check_state_file() {
  local name="$1"
  local path="$STATE_DIR/$name.json"
  if [[ ! -f "$path" ]]; then
    return
  fi
  local state
  state=$(python3 -c "import json; print(json.load(open('$path')).get('state','?'))" 2>/dev/null)
  if [[ -z "$state" ]]; then
    echo "  [WARN] $name.json unreadable"
    return
  fi
  if [[ "$state" == "error" ]]; then
    echo "  [FAIL] $name reports state=error"
    fail=1
  else
    echo "  [ OK ] $name state=$state"
  fi
}

for svc in camera_primary camera_left camera_right sensors lumen epaper watchdog led; do
  check_state_file "$svc"
done

echo "-- disk space --"
if [[ -d "$DATA_DIR" ]]; then
  free_gb=$(df --output=avail -BG "$DATA_DIR" 2>/dev/null | tail -1 | tr -dc '0-9')
  if [[ -z "$free_gb" ]]; then
    echo "  [WARN] could not determine free space on $DATA_DIR"
  else
    echo "  free space on $DATA_DIR: ${free_gb}GB"
    if (( free_gb < MIN_FREE_GB )); then
      echo "  [FAIL] less than ${MIN_FREE_GB}GB free"
      fail=1
    else
      echo "  [ OK ] sufficient free space"
    fi
  fi
else
  echo "  [WARN] $DATA_DIR not found"
fi

echo "-- clock sanity --"
current_year=$(date -u +%Y)
if (( current_year < 2025 )); then
  echo "  [FAIL] system clock looks wrong (year=$current_year) -- sync it from your laptop first:"
  echo "         ssh pi@<host> \"sudo date -u -s '\$(date -u +%Y-%m-%dT%H:%M:%S)' && sudo hwclock -w\""
  fail=1
else
  echo "  [ OK ] system clock: $(date -u --iso-8601=seconds)"
fi

echo
if [[ "$fail" -ne 0 ]]; then
  echo "One or more checks FAILED. Fix the issue(s) above before arming. Nothing changed."
  exit 1
fi

echo "All checks passed."
read -r -p "Arm for deployment? This disables Wi-Fi/Bluetooth and ends this SSH session. Type 'yes' to continue: " confirm
if [[ "$confirm" != "yes" ]]; then
  echo "Aborted -- no changes made."
  exit 1
fi

echo "Logging arm event..."
python3 -c "
import sys
sys.path.insert(0, '$BUBBLECAM_LIB')
from bubblecam import state_lib
state_lib.write_state('system', 'armed')
"

echo "Stopping avahi-daemon (mDNS)..."
systemctl stop avahi-daemon.service 2>/dev/null
systemctl disable avahi-daemon.service 2>/dev/null

echo "Disabling Wi-Fi and Bluetooth radios -- this will end the SSH session..."
nmcli radio wifi off 2>/dev/null
nmcli radio bluetooth off 2>/dev/null
rfkill block wifi 2>/dev/null
rfkill block bluetooth 2>/dev/null

echo "Armed. Safe to seal the enclosure."
