#!/usr/bin/env bash
# laptop VNC + Chromium boot acceptance test.
#
# Asserts the four green conditions from .tasks/929 §Verification:
#   1. The configured Chromium binary's realpath does NOT contain `/snap/`.
#   2. The configured binary is on PATH and executable.
#   3. http://127.0.0.1:${cdpPort}/json/version returns the Chromium version JSON.
#   4. ~/.{configDir}/logs/vnc-boot.log ends with `VNC + browser stack running`
#      with no preceding `Chromium failed to start` line.
#
# Exits non-zero on any assertion failure so this script is wired into the
# create-maxy post-install gate — any package bump that re-introduces
# snap-confined Chromium fails before publish (`feedback_no_admin_upgrade_path.md`).
#
# Usage (production / post-install): test-laptop-vnc-boot.sh
# Usage (CI / dev shell):            MAXY_PLATFORM_ROOT=/path/to/maxy/platform test-laptop-vnc-boot.sh

set -uo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PLATFORM_ROOT="${MAXY_PLATFORM_ROOT:-$(dirname "$SCRIPT_DIR")}"
BRAND_JSON="${PLATFORM_ROOT}/config/brand.json"
CHROMIUM_BIN_FILE="${PLATFORM_ROOT}/config/chromium-binary.path"

fail()   { echo "FAIL: $*" >&2; exit 1; }
pass()   { echo "OK: $*"; }

# --- Resolve config: brand persistDir + cdpPort. brand.json is mandatory.
[ -r "$BRAND_JSON" ] || fail "${BRAND_JSON} unreadable"
command -v jq >/dev/null 2>&1 || fail "jq not on PATH (apt install jq)"
CONFIG_DIR=$(jq -r '.configDir // ".maxy"' "$BRAND_JSON")
# brand.json is the single source of truth for cdpPort at
# runtime; a missing field is a doctrinal violation, not a fallback.
if ! CDP_PORT=$(jq -er '.cdpPort' "$BRAND_JSON" 2>/dev/null); then
  _keys=$(jq -r 'keys | join(",")' "$BRAND_JSON" 2>/dev/null || echo "unparseable")
  _brand=$(echo "$CONFIG_DIR" | sed 's/^\.//')
  echo "[test-laptop-vnc-boot] error reason=cdp-port-unresolved brand=$_brand path=$BRAND_JSON field=cdpPort json_keys=$_keys" >&2
  exit 1
fi
PERSIST_DIR="${HOME}/${CONFIG_DIR}"
VNC_LOG="${PERSIST_DIR}/logs/vnc-boot.log"

# --- Assertion 1: chromium-binary.path realpath is non-snap.
[ -r "$CHROMIUM_BIN_FILE" ] || fail "${CHROMIUM_BIN_FILE} missing — installer did not write it"
CHROMIUM_BIN="$(head -n1 "$CHROMIUM_BIN_FILE" | tr -d '[:space:]')"
[ -n "$CHROMIUM_BIN" ] || fail "${CHROMIUM_BIN_FILE} is empty"
[ -x "$CHROMIUM_BIN" ] || fail "configured Chromium ${CHROMIUM_BIN} is not executable"
CHROMIUM_REALPATH="$(readlink -f "$CHROMIUM_BIN" 2>/dev/null || echo "$CHROMIUM_BIN")"
case ":$(echo "$CHROMIUM_REALPATH" | tr '/' ':'):" in
  *:snap:*) fail "${CHROMIUM_BIN} resolves to ${CHROMIUM_REALPATH} (snap-confined — AppArmor will deny SingletonLock writes)" ;;
esac
pass "[1/4] Chromium binary ${CHROMIUM_BIN} → realpath=${CHROMIUM_REALPATH} (non-snap)"

# --- Assertion 2: configured binary is the same as `which chromium` resolves
#                  to OR an absolute path bypassing PATH. Skipped if the
#                  configured path is absolute and executable (the only thing
#                  callers actually require). The PATH check is informational.
if [ "${CHROMIUM_BIN#/}" = "$CHROMIUM_BIN" ]; then
  fail "${CHROMIUM_BIN_FILE} contains a relative path — must be absolute"
fi
pass "[2/4] ${CHROMIUM_BIN} is an absolute, executable path"

# --- Assertion 3: CDP endpoint responds with version JSON.
CDP_URL="http://127.0.0.1:${CDP_PORT}/json/version"
CDP_RESP="$(curl -fsS -m 5 "$CDP_URL" 2>&1 || true)"
if ! echo "$CDP_RESP" | jq -e '.Browser // empty' >/dev/null 2>&1; then
  fail "[3/4] ${CDP_URL} did not return Chromium version JSON. Response: ${CDP_RESP:0:500}"
fi
pass "[3/4] ${CDP_URL} returns Chromium version JSON"

# --- Assertion 4: vnc-boot.log ends with the success line and never
#                  emitted `Chromium failed to start` after the most recent
#                  `[vnc.sh] start` marker.
[ -r "$VNC_LOG" ] || fail "[4/4] ${VNC_LOG} unreadable"
LAST_START_LINE=$(grep -n "\[vnc.sh\] start " "$VNC_LOG" | tail -n1 | cut -d: -f1)
if [ -z "$LAST_START_LINE" ]; then
  fail "[4/4] ${VNC_LOG} contains no [vnc.sh] start marker — vnc.sh has not been invoked yet"
fi
TAIL_AFTER_START=$(tail -n +"$LAST_START_LINE" "$VNC_LOG")
if echo "$TAIL_AFTER_START" | grep -q "Chromium failed to start"; then
  fail "[4/4] ${VNC_LOG} since last start contains 'Chromium failed to start' (boot regression)"
fi
if ! echo "$TAIL_AFTER_START" | grep -q "VNC + browser stack running"; then
  fail "[4/4] ${VNC_LOG} since last start has no 'VNC + browser stack running' line — VNC boot incomplete"
fi
pass "[4/4] ${VNC_LOG} reports VNC + browser stack running with no Chromium failed-to-start"

echo "acceptance: PASS (4/4)"
