#!/usr/bin/env bash
# `npm run check:all` (before a release): copies the committed HEAD (plus the installed Composer vendors, which
# hold the private vector SDK) to the AI box and runs every suite there in containers (ci/remote-check.sh).
# `npm run check:related` (before a track's merge) runs only the suites its plan selects, the same way (--plan).
#
#   npm run check:all              all suites; real-provider tests run when .env.test has keys
#   npm run check:all -- --no-paid  the same without .env.test, so no paid API is called
#   npm run check:all -- --local    the same suites in Docker on this Mac (when the box is not available)
#   npm run check:all -- --wp-min   adds the WP-CLI suite on WordPress 6.6 and PHP 8.0 (the minimum)
#   ci/run-remote.sh --plan <file>  only the steps a plan from scripts/test-plan.mjs selects, with its filters
#
# KIMAAI_CI_HOST overrides the SSH host (default: aibox), KIMAAI_CI_DIR the folder there
# (default: /srv/work/ci/kimaai, provisioned by nabiHomeNetwork provision/tasks/ci.yml).
set -euo pipefail

HOST="${KIMAAI_CI_HOST:-aibox}"
ROOT="$(git rev-parse --show-toplevel)"
cd "$ROOT"

PAID=1
LOCAL=0
WP_MIN=0
PLAN=""
while [ $# -gt 0 ]; do
  case "$1" in
    --no-paid) PAID=0 ;;
    --paid) PAID=1 ;;
    --local) LOCAL=1 ;;
    --wp-min) WP_MIN=1 ;;
    --plan) PLAN="${2:?--plan needs a file}"; shift ;;
    *) echo "Unknown option: $1" >&2; exit 2 ;;
  esac
  shift
done

SHA="$(git rev-parse --short HEAD)"
RUN="$SHA-$(date +%s)"
if [ "$LOCAL" = 1 ]; then
  BASE="${TMPDIR:-/tmp}/kimaai-ci"
  REMOTE_DIR="$BASE/$RUN"
  REMOTE_ENV="$BASE/$RUN.env"
  mkdir -p "$BASE"
  # The same commands as on the box, run here. Ollama: the box's over the tailnet unless set.
  on_host() { KIMAAI_CI_OLLAMA_URL="${KIMAAI_CI_OLLAMA_URL:-http://aibox.tailda25c5.ts.net:11434/v1}" bash -c "$1"; }
else
  REMOTE_DIR="${KIMAAI_CI_DIR:-/srv/work/ci/kimaai}/$RUN"
  # Secrets go to /dev/shm (memory), never to the box's disk.
  REMOTE_ENV="/dev/shm/kimaai-ci-$RUN.env"
  on_host() { ssh -o ConnectTimeout=10 -o ServerAliveInterval=15 -o ServerAliveCountMax=4 "$HOST" "$1"; }
fi

if [ -n "$(git status --porcelain --untracked-files=no)" ]; then
  echo "Note: uncommitted changes are not checked; this runs the committed HEAD ($SHA)."
fi

if [ ! -d vendor/bin ] || [ ! -d premium/vendor ]; then
  echo "Install the Composer dependencies first: composer install && composer install --working-dir=premium" >&2
  exit 1
fi
# The vendors are copied as they are, so they must match the lock files.
for dir in . premium; do
  if ! composer install --dry-run --no-interaction --working-dir="$dir" 2>&1 | grep -q 'Nothing to install, update or remove'; then
    echo "The Composer dependencies in $dir do not match its composer.lock: run composer install --working-dir=$dir" >&2
    exit 1
  fi
done

# A line to ci/remote-check.sh every two seconds, until it has finished. When the lines stop (Ctrl-C, a dropped
# connection), it stops the run and removes what it left on the host.
heartbeat() {
  trap '' PIPE
  while echo 2>/dev/null; do
    sleep 2
  done
}

cleanup() {
  # After an interrupted run, wait (up to a minute) until the host has stopped it, then remove what is left.
  on_host "for i in \$(seq 60); do pgrep -f 'remote-check[.]sh $REMOTE_DIR' >/dev/null || break; sleep 1; done" || true
  # Bring every step's full log back to the Mac (.ci-logs/, git-ignored) before removing the checkout.
  rm -rf .ci-logs
  on_host "tar -c -C '$REMOTE_DIR' .ci-logs 2>/dev/null" | tar -x -C "$ROOT" 2>/dev/null || true
  on_host "rm -f '$REMOTE_ENV'; rm -rf '$REMOTE_DIR'" || true
  [ -d .ci-logs ] && echo "Full logs: .ci-logs/"
}
trap cleanup EXIT
trap 'exit 130' INT TERM HUP

echo "Copying $SHA to $([ "$LOCAL" = 1 ] && echo "this Mac" || echo "$HOST"):$REMOTE_DIR"
on_host "mkdir '$REMOTE_DIR'"
git archive --format=tar HEAD | on_host "tar -x -C '$REMOTE_DIR'"
tar -c vendor premium/vendor | on_host "tar -x -C '$REMOTE_DIR'"

PLAN_ARG=""
if [ -n "$PLAN" ]; then
  on_host "cat > '$REMOTE_DIR/.ci-plan.json'" < "$PLAN"
  PLAN_ARG="$REMOTE_DIR/.ci-plan.json"
fi

ENV_ARG=""
if [ "$PAID" = 1 ] && [ -f .env.test ]; then
  on_host "umask 077 && cat > '$REMOTE_ENV'" < .env.test
  ENV_ARG="$REMOTE_ENV"
fi

heartbeat | on_host "KIMAAI_CI_WATCH=1 KIMAAI_CI_WP_MIN=$WP_MIN KIMAAI_CI_PLAN='$PLAN_ARG' bash '$REMOTE_DIR/ci/remote-check.sh' '$REMOTE_DIR' '$ENV_ARG'"
