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

LAB_ROOT=${W3CS_LAB_ROOT:-/home/ubuntu/w3cs-lab}
PROFILE_ROOT=${W3CS_ENGINE_PROFILE_ROOT:-"$LAB_ROOT/engine-profiles"}

install_profile() {
  local profile=$1
  local artifact=$2
  local archive_sha256=$3
  local archive_root=$4
  local destination="$PROFILE_ROOT/$profile"

  if [[ -f "$destination/installed.json" ]]; then
    python3 - "$destination/installed.json" "$archive_sha256" <<'PY'
import json
import sys
with open(sys.argv[1], encoding="utf-8") as source:
    installed = json.load(source)
if installed.get("artifactSha256") != sys.argv[2]:
    raise SystemExit("installed engine profile has the wrong artifact hash")
PY
    return
  fi
  [[ -f "$artifact" ]] || {
    echo "engine profile artifact is missing: $artifact" >&2
    exit 2
  }
  local actual
  actual=$(sha256sum "$artifact" | cut -d' ' -f1)
  [[ "$actual" == "$archive_sha256" ]] || {
    echo "engine profile artifact checksum mismatch: $profile" >&2
    exit 3
  }
  [[ ! -e "$destination" ]] || {
    echo "refusing to replace an unrecognized engine profile: $destination" >&2
    exit 4
  }

  local temporary
  temporary=$(mktemp -d "$PROFILE_ROOT/.${profile}.XXXXXX")
  trap 'rm -rf -- "$temporary"' RETURN
  tar -xzf "$artifact" -C "$temporary"
  local source="$temporary/$archive_root"
  [[ -f "$source/manifest.json" && -d "$source/files" ]] || {
    echo "engine profile archive has an invalid layout: $profile" >&2
    exit 5
  }
  python3 - "$source/manifest.json" "$source/files" <<'PY'
import hashlib
import json
import pathlib
import sys

manifest_path = pathlib.Path(sys.argv[1])
files_root = pathlib.Path(sys.argv[2])
with manifest_path.open(encoding="utf-8") as source:
    manifest = json.load(source)
expected = manifest.get("installation", {}).get("files", {})
if set(expected) != {"Storm.dll", "War3Patch.mpq", "game.dll", "war3.exe"}:
    raise SystemExit("engine profile manifest has an unexpected file set")
for name, record in expected.items():
    path = files_root / name
    digest = hashlib.sha256(path.read_bytes()).hexdigest()
    if digest != record.get("sha256") or path.stat().st_size != record.get("bytes"):
        raise SystemExit(f"engine profile file differs: {name}")
PY
  mkdir -p "$destination"
  cp -a "$source/files" "$destination/files"
  cp "$source/manifest.json" "$destination/manifest.json"
  python3 - "$destination/manifest.json" "$destination/installed.json" \
      "$archive_sha256" <<'PY'
import json
import sys
with open(sys.argv[1], encoding="utf-8") as source:
    manifest = json.load(source)
with open(sys.argv[2], "w", encoding="utf-8") as output:
    json.dump({
        "schema": 1,
        "artifactSha256": sys.argv[3],
        "rawReplayVersion": manifest["rawReplayVersion"],
        "patchFamily": manifest["patchFamily"],
        "materializedFileVersion": manifest["materializedFileVersion"],
    }, output, sort_keys=True)
    output.write("\n")
PY
  chmod -R a-w "$destination"
  trap - RETURN
  rm -rf -- "$temporary"
}

mkdir -p "$PROFILE_ROOT"
install_profile classic-124ab \
  "$LAB_ROOT/wc3-classic-124ab-runtime-proof-v1.tgz" \
  0c5de0d77042f4f113d26ed600b7683baa0627e98d1004f3593427efc1dc77b9 \
  classic-124-ab-overlay
install_profile classic-124cde \
  "$LAB_ROOT/wc3-classic-124cde-runtime-proof-v1.tgz" \
  59f5862203ac66bdf2154e5a6f4583e7cd1de5db61c715544f234e95d4951bf2 \
  classic-124-cde-overlay

echo "WC3 engine profiles are ready at $PROFILE_ROOT"
