#!/usr/bin/env bash
# service-kicad deploy — DEFAULT channel (KiCad 10).
#
# Run ONCE on a fresh default-light container at carbon.adom.inc.
# This script is the canonical primary deploy; the v10 PPA overwrites
# the v9 `kicad` package so a host can be on exactly one channel at a
# time. For a v9 fallback container, use [`deploy-v9.sh`](deploy-v9.sh)
# on a separate host.

set -euo pipefail

REPO_DIR="$HOME/service-kicad"

echo "==> service-kicad deploy starting (default channel — KiCad 10)"
echo "==> repo dir: $REPO_DIR"

# Hard guard: refuse to run on a host that already has v9 installed.
# Mixing PPAs would leave kicad-cli in a half-upgraded state. The
# in-place v9 → v10 swap of the original prod container was a one-time
# event done outside this script.
if dpkg -l kicad 2>/dev/null | awk '/^ii/ {print $3}' | grep -q '^9\.'; then
  echo "==> ERROR: KiCad 9 is already installed on this host. Provision a separate container, or run deploy-v9.sh if you actually want the fallback channel." >&2
  exit 1
fi

# 1. System deps — KiCad 10 + libraries.
echo "==> installing apt packages (KiCad 10 + libraries + cron)"
sudo apt-get update
sudo apt-get install -y \
  software-properties-common curl build-essential pkg-config git jq cron
sudo add-apt-repository -y ppa:kicad/kicad-10.0-releases
sudo apt-get update
sudo apt-get install -y kicad kicad-symbols kicad-footprints kicad-packages3d

# Library overlay — prefer the upstream `10.0` stable branch, fall back
# to master if it doesn't exist yet. (Library repos branch when stable
# cuts; master is the dev branch that may already be drifting toward 11.)
LIB_BASE=/opt
for repo in kicad-footprints kicad-symbols kicad-packages3D; do
  dir="$LIB_BASE/${repo,,}-upstream"   # lowercase
  if [ ! -d "$dir/.git" ]; then
    echo "==> cloning upstream $repo → $dir (prefer branch 10.0)"
    if ! sudo git clone --depth 1 --branch 10.0 "https://github.com/KiCad/$repo.git" "$dir" 2>/dev/null; then
      echo "==>   no 10.0 branch yet; falling back to master"
      sudo git clone --depth 1 "https://github.com/KiCad/$repo.git" "$dir"
    fi
  else
    echo "==> upstream $repo already at $dir; refreshing"
    sudo git -C "$dir" pull --quiet --ff-only || true
  fi
done

# Persist KICAD_*_DIR for service-kicad-api (read at startup).
sudo tee /etc/default/service-kicad >/dev/null <<'EOF'
KICAD_FOOTPRINTS_DIR=/opt/kicad-footprints-upstream
KICAD_SYMBOLS_DIR=/opt/kicad-symbols-upstream
KICAD_PACKAGES3D_DIR=/opt/kicad-packages3d-upstream
EOF

# Weekly refresh — Mondays @ 04:00 UTC.
sudo tee /etc/cron.d/kicad-lib-pull >/dev/null <<'EOF'
0 4 * * 1 root for d in /opt/kicad-footprints-upstream /opt/kicad-symbols-upstream /opt/kicad-packages3d-upstream; do git -C "$d" pull --quiet --ff-only 2>&1 | logger -t kicad-lib-pull; done
EOF
sudo chmod 0644 /etc/cron.d/kicad-lib-pull

# default-light has sshd as PID 1 (no systemd) — cron has to be
# launched manually and kept alive by the user.
if ! pgrep -x cron >/dev/null; then
  echo "==> starting cron daemon"
  sudo /usr/sbin/cron
fi

# 2. Rust toolchain
echo "==> installing rustup"
if ! command -v rustup &>/dev/null; then
  curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable
  source "$HOME/.cargo/env"
fi

# 3. Clone + build the service API. Same source as v9 — the binary is
# channel-agnostic; it shells to whichever kicad-cli is on $PATH.
if [ ! -d "$REPO_DIR" ]; then
  echo "==> cloning service-kicad"
  git clone https://github.com/adom-inc/service-kicad.git "$REPO_DIR"
fi
cd "$REPO_DIR"
git pull --rebase origin main

echo "==> building service-kicad-api (http server) and service-kicad (cli)"
cargo build --release --bin service-kicad-api --bin service-kicad
sudo install "$REPO_DIR/target/release/service-kicad-api" /usr/local/bin/service-kicad-api
sudo install "$REPO_DIR/target/release/service-kicad"     /usr/local/bin/service-kicad

# 4. Install watchdog cron (same script as v9 — rebuilds whatever's in main)
echo "==> installing watchdog cron"
mkdir -p "$HOME/.cache"
CRON_LINE="*/2 * * * * $REPO_DIR/watchdog.sh >> $HOME/.cache/service-kicad-watchdog.log 2>&1"
set +e
( crontab -l 2>/dev/null | grep -v "service-kicad/watchdog.sh" ; echo "$CRON_LINE" ) | crontab -
cron_exit=$?
set -e
[ $cron_exit -ne 0 ] && { echo "crontab install failed (exit $cron_exit)"; exit $cron_exit; }

# 5. First launch + health check
echo "==> starting service-kicad-api"
sudo touch /var/log/service-kicad.log && sudo chown "$USER" /var/log/service-kicad.log
pkill -x service-kicad-api || true
set -a; [ -f /etc/default/service-kicad ] && . /etc/default/service-kicad; set +a
nohup /usr/local/bin/service-kicad-api >> /var/log/service-kicad.log 2>&1 &
sleep 3
if curl -sf http://127.0.0.1:8780/health | jq -e '.ok' > /dev/null; then
  echo "==> service-kicad (v10) is healthy ✓"
  curl -sf http://127.0.0.1:8780/health | jq
else
  echo "==> service-kicad health check FAILED" >&2
  exit 1
fi

echo "==> deploy complete (KiCad 10 channel)"
