#!/usr/bin/env bash
# Manual: HEVC remote re-entry check for operator-driven lab recovery; not part of CI.
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
STAMP="$(date +%Y%m%d-%H%M%S)"
REMOTE_HOST="${LESAVKA_HEVC_REENTRY_HOST:-theia}"
REMOTE_REPO="${LESAVKA_HEVC_REENTRY_REMOTE_REPO:-/home/theia/Development/lesavka-codex}"
MODE="${LESAVKA_HEVC_REENTRY_MODE:-1280x720@30}"
CODEC="${LESAVKA_HEVC_REENTRY_CODEC:-hevc}"
SYNC_REPO="${LESAVKA_HEVC_REENTRY_SYNC:-0}"
BUILD_RELEASE="${LESAVKA_HEVC_REENTRY_BUILD:-0}"
DEPLOY="${LESAVKA_HEVC_REENTRY_DEPLOY:-0}"
RECONFIGURE="${LESAVKA_HEVC_REENTRY_RECONFIGURE:-0}"
OUTPUT_DIR="${LESAVKA_HEVC_REENTRY_OUTPUT_DIR:-/tmp/lesavka-hevc-reentry-${STAMP}}"
RUN_LOG="${OUTPUT_DIR}/hevc-reentry.log"
WAIT_SECONDS="${LESAVKA_HEVC_REENTRY_WAIT_SECONDS:-0}"
WAIT_INTERVAL_SECONDS="${LESAVKA_HEVC_REENTRY_WAIT_INTERVAL_SECONDS:-15}"
SSH_OPTS=${SSH_OPTS:-"-o BatchMode=yes -o ConnectTimeout=8"}

mkdir -p "${OUTPUT_DIR}"

echo "==> HEVC remote re-entry check"
echo "   ↪ host=${REMOTE_HOST}"
echo "   ↪ remote_repo=${REMOTE_REPO}"
echo "   ↪ mode=${MODE} codec=${CODEC}"
echo "   ↪ sync=${SYNC_REPO} build=${BUILD_RELEASE} deploy=${DEPLOY} reconfigure=${RECONFIGURE}"
echo "   ↪ wait_seconds=${WAIT_SECONDS} wait_interval_seconds=${WAIT_INTERVAL_SECONDS}"
echo "   ↪ run_log=${RUN_LOG}"
echo "   ↪ sudo is non-interactive only; this script will not prompt for passwords"

run_ssh() {
  # shellcheck disable=SC2086
  ssh ${SSH_OPTS} "${REMOTE_HOST}" "$@"
}

sync_repo_to_remote() {
  if command -v rsync >/dev/null 2>&1 && run_ssh 'command -v rsync >/dev/null 2>&1'; then
    rsync -az --delete \
      --exclude .git \
      --exclude target \
      --exclude '*.profraw' \
      "${REPO_ROOT}/" "${REMOTE_HOST}:${REMOTE_REPO}/"
    return
  fi

  echo "   ↪ rsync unavailable on one side; falling back to git-file tar-over-SSH sync without remote delete"
  if command -v git >/dev/null 2>&1; then
    (
      cd "${REPO_ROOT}"
      git ls-files -z --cached --others --exclude-standard \
        | tar --null -T - -czf -
    ) | run_ssh "mkdir -p '${REMOTE_REPO}' && tar -xzf - -C '${REMOTE_REPO}'"
    return
  fi

  echo "   ↪ git unavailable locally; using strict source tar excludes"
  (
    cd "${REPO_ROOT}"
    tar \
      --exclude './.git' \
      --exclude './target' \
      --exclude './target/*' \
      --exclude '*/target' \
      --exclude '*/target/*' \
      --exclude '*.profraw' \
      -czf - .
  ) | run_ssh "mkdir -p '${REMOTE_REPO}' && tar -xzf - -C '${REMOTE_REPO}'"
}

wait_for_remote() {
  local deadline now attempt

  if [[ "${WAIT_SECONDS}" == "0" ]]; then
    run_ssh 'date -Is'
    return
  fi

  deadline=$((SECONDS + WAIT_SECONDS))
  attempt=1
  while true; do
    echo "== remote reachability attempt ${attempt} =="
    if run_ssh 'date -Is'; then
      return
    fi
    now="${SECONDS}"
    if (( now >= deadline )); then
      echo "remote host did not become reachable within ${WAIT_SECONDS}s" >&2
      return 1
    fi
    sleep "${WAIT_INTERVAL_SECONDS}"
    attempt=$((attempt + 1))
  done
}

(
  echo "== remote reachability =="
  wait_for_remote

  echo "== lesavka helper status =="
  run_ssh 'sudo -n /usr/local/sbin/lesavka-dev-install status'

  if [[ "${SYNC_REPO}" == "1" ]]; then
    echo "== syncing local repo to remote workspace =="
    sync_repo_to_remote
  fi

  if [[ "${BUILD_RELEASE}" == "1" ]]; then
    echo "== remote release build =="
    run_ssh "cd '${REMOTE_REPO}' && cargo build --release --bin lesavka-server --bin lesavka-uvc"
  fi

  if [[ "${DEPLOY}" == "1" ]]; then
    echo "== remote deploy =="
    run_ssh 'sudo -n /usr/local/sbin/lesavka-dev-install deploy'
  fi

  if [[ "${RECONFIGURE}" == "1" ]]; then
    echo "== remote HEVC reconfigure =="
    run_ssh "sudo -n /usr/local/sbin/lesavka-dev-install reconfigure '${MODE}' '${CODEC}'"
  fi

  echo "== final status =="
  run_ssh 'sudo -n /usr/local/sbin/lesavka-dev-install status'
) 2>&1 | tee "${RUN_LOG}"

echo "==> done"
echo "artifact_dir: ${OUTPUT_DIR}"
echo "run_log: ${RUN_LOG}"
