#!/bin/bash
set -euo pipefail

usage() {
  echo "usage: run-realm.sh <cloud|private>" >&2
  exit 64
}

fail() {
  echo "error: $1" >&2
  exit "${2:-1}"
}

require_regular_file() {
  local path="$1"
  local mode

  [[ -f "$path" ]] || fail "required file missing" 66
  [[ ! -L "$path" ]] || fail "unsafe file path" 66
  mode="$(/usr/bin/stat -f '%OLp' "$path")"
  [[ "$mode" == "600" ]] || fail "unsafe file mode" 66
}

resolve_strict() {
  /usr/bin/python3 - "$1" <<'PY'
from pathlib import Path
import sys

print(Path(sys.argv[1]).resolve(strict=True))
PY
}

realm="${1:-}"
[[ -n "$realm" ]] || usage
shift || true
[[ $# -eq 0 ]] || usage
case "$realm" in
  cloud)
    host="100.117.228.68"
    port="1933"
    workspace="/Volumes/AXAGON/Ahel/knowledge/cloud"
    config_path="/Users/admin/.config/ahel/openviking/cloud.ov.conf.json"
    root_key_path="/Users/admin/.config/ahel/openviking/cloud.root-api-key"
    openrouter_env="/Users/admin/.config/ahel/openviking/openrouter.env"
    ;;
  private)
    host="127.0.0.1"
    port="1934"
    workspace="/Volumes/AXAGON/Ahel/knowledge/private"
    config_path="/Users/admin/.config/ahel/openviking/private.ov.conf.json"
    root_key_path="/Users/admin/.config/ahel/openviking/private.root-api-key"
    openrouter_env=""
    ;;
  *)
    usage
    ;;
esac

volume="/Volumes/AXAGON"
uuid_file="/Users/admin/.config/ahel/openviking/axagon.volume-uuid"
server_bin="/Users/admin/.local/share/ahel/openviking-venv/bin/openviking-server"
repo_root="/Users/admin/dev/ahel"

[[ -d "$volume" ]] || fail "AXAGON volume unavailable" 65
require_regular_file "$uuid_file"
require_regular_file "$root_key_path"
[[ -f "$config_path" && ! -L "$config_path" ]] || fail "realm runtime config missing" 66
[[ -x "$server_bin" && ! -L "$server_bin" ]] || fail "OpenViking runtime missing" 69
[[ -d "$repo_root" && ! -L "$repo_root" ]] || fail "repo root unavailable" 69

actual_uuid="$(/usr/sbin/diskutil info -plist "$volume" | /usr/bin/plutil -extract VolumeUUID raw -o - -)"
expected_uuid="$(/usr/bin/tr -d '[:space:]' < "$uuid_file")"
[[ -n "$actual_uuid" && "$actual_uuid" == "$expected_uuid" ]] || fail "AXAGON identity mismatch" 65

resolved_workspace="$(resolve_strict "$workspace")"
[[ "$resolved_workspace" == /Volumes/AXAGON/* ]] || fail "realm workspace escaped AXAGON" 65

export OPENVIKING_ROOT_API_KEY
OPENVIKING_ROOT_API_KEY="$(/bin/cat "$root_key_path")"
[[ -n "$OPENVIKING_ROOT_API_KEY" ]] || fail "empty realm api key" 66

if [[ "$realm" == "cloud" ]]; then
  require_regular_file "$openrouter_env"
  set -a
  # shellcheck source=/dev/null
  . "$openrouter_env"
  set +a
  [[ -n "${OPENROUTER_API_KEY:-}" ]] || fail "cloud provider key unavailable" 66
else
  unset OPENROUTER_API_KEY || true
fi

cd "$repo_root"
exec "$server_bin" --config "$config_path" --host "$host" --port "$port" --workers 1
