#!/usr/bin/env bash
set -euo pipefail

host="${WHETSTONE_VPS_HOST:-vps2}"
site_root="/opt/whetstone-tools"
current_link="${site_root}/current"
release_id="brand-$(date -u +%Y%m%d%H%M%SZ)"
release_dir="${site_root}/releases/${release_id}"
remote_bundle="/tmp/whetstone-brand-${release_id}.tgz"
pytest_dir="/tmp/whetstone-brand-pytest-${release_id}"
project_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
static_root="${project_root}/whetstone-ui"
bundle="$(mktemp --suffix=.tgz)"
home_probe="$(mktemp)"
css_probe="$(mktemp)"
previous="$(ssh "${host}" readlink -f "${current_link}")"
switched=0

cleanup() {
  local status=$?
  rm -f -- "${bundle}" "${home_probe}" "${css_probe}"
  ssh "${host}" rm -f -- "${remote_bundle}" >/dev/null 2>&1 || true
  if [[ "${pytest_dir}" == /tmp/whetstone-brand-pytest-* ]]; then
    ssh "${host}" rm -rf -- "${pytest_dir}" >/dev/null 2>&1 || true
  fi
  if [[ ${status} -ne 0 && ${switched} -eq 1 ]]; then
    ssh "${host}" sudo ln -sfn "${previous}" "${current_link}.rollback"
    ssh "${host}" sudo mv -Tf "${current_link}.rollback" "${current_link}"
    printf 'Rolled back Whetstone to %s\n' "${previous}" >&2
  fi
  exit "${status}"
}
trap cleanup EXIT

for file in index.html styles.css for-agents.html; do
  [[ -f "${static_root}/${file}" ]] || { printf 'Missing %s\n' "${static_root}/${file}" >&2; exit 1; }
done

tar -C "${static_root}" -czf "${bundle}" index.html styles.css for-agents.html
scp "${bundle}" "${host}:${remote_bundle}"

ssh "${host}" sudo cp -a --reflink=auto "${previous}" "${release_dir}"
ssh "${host}" sudo tar -xzf "${remote_bundle}" -C "${release_dir}/src/bcv/toolbox_static"
ssh "${host}" sudo chown root:root \
  "${release_dir}/src/bcv/toolbox_static/index.html" \
  "${release_dir}/src/bcv/toolbox_static/styles.css" \
  "${release_dir}/src/bcv/toolbox_static/for-agents.html"
ssh "${host}" sudo chmod 0644 \
  "${release_dir}/src/bcv/toolbox_static/index.html" \
  "${release_dir}/src/bcv/toolbox_static/styles.css" \
  "${release_dir}/src/bcv/toolbox_static/for-agents.html"

ssh "${host}" grep -q Cyberelf "${release_dir}/src/bcv/toolbox_static/index.html"
ssh "${host}" grep -q console-scan "${release_dir}/src/bcv/toolbox_static/styles.css"

ssh "${host}" python3 -m pip install --quiet --disable-pip-version-check --target "${pytest_dir}" pytest
ssh "${host}" env "PYTHONPATH=${pytest_dir}:${release_dir}/src" \
  python3 -m pytest -p no:cacheprovider -q "${release_dir}/tests/test_toolbox_service.py"

ssh "${host}" sudo ln -sfn "${release_dir}" "${current_link}.next"
ssh "${host}" sudo mv -Tf "${current_link}.next" "${current_link}"
switched=1

curl --fail --silent --show-error --retry 5 --retry-delay 1 \
  --output "${home_probe}" 'https://whetstone.cyberelf.link/'
grep -q 'Cyberelf Labs // Whetstone' "${home_probe}"
curl --fail --silent --show-error --retry 5 --retry-delay 1 \
  --output "${css_probe}" 'https://whetstone.cyberelf.link/styles.css?v=cyberelf-20260722-r3'
grep -q -- '--cyan: #43f5e7' "${css_probe}"
curl --fail --silent --show-error --retry 5 --retry-delay 1 \
  'https://whetstone.cyberelf.link/api/health' | python3 -c \
  'import json,sys; d=json.load(sys.stdin); assert d["status"] == "ok"; assert d["stateless"] is True; assert d["private_bank_loaded"] is False; assert d["tools"] == 8'

printf 'Whetstone release: %s\n' "${release_dir}"
printf 'Previous release: %s\n' "${previous}"
