#!/bin/sh
# Generated by site-kungfu-tech from one exact signed Alpha.2 publication.
# Catalog: sha256:ea9076eb1ea8b1ee486dd9cee5917a7bed689af502fc57487a274fd22dd4b93e
set -eu

channel='alpha'
version='4.0.0-alpha.2'
source_commit='b0cff8236b8b3746f8028b9d519ed3b0e26096c9'
channel_url='https://kungfu.tech/channels/alpha/8c031dd420e15ddde5b4e751cb4dcc3c0a2d4bd67956d295918e21165de6abdd/index.json'
channel_sha256='8b01d6aab5d71949da2a9ff90f4d05fb725e9338979b52e38454ca653b7ee3ca'
trusted_key='ed25519-3c473c24ca261745=bNB6syHpgY0RKMHPKUhekyQupwgvtwqQ6qqrUV2ecfQ='
catalog_root='sha256:ea9076eb1ea8b1ee486dd9cee5917a7bed689af502fc57487a274fd22dd4b93e'
release_passport_root='sha256:63116c9c3f035025ae0166863cc5ef43dab67dfba153d039a09d428f02dbe2c0'
install_root=${XDG_DATA_HOME:-"$HOME/.local/share"}/kungfu/product
cache_root=${XDG_CACHE_HOME:-"$HOME/.cache"}/kungfu/installers
bin_dir="$HOME/.local/bin"
requested_channel=$channel
requested_version=
dry_run=0
verbose=0
rollback=0
noninteractive=0

usage() {
  printf '%s\n' "usage: install.sh [--channel alpha] [--version VERSION] [--install-dir DIR] [--cache-dir DIR] [--bin-dir DIR] [--rollback] [--dry-run] [--no-path] [--yes] [--ci] [--verbose]"
}
log() { printf '%s\n' "kungfu-install: $*" >&2; }
debug() { [ "$verbose" -eq 0 ] || log "$@"; }
fail() { log "error[$1]: $2"; exit 1; }

while [ "$#" -gt 0 ]; do
  case "$1" in
    --channel) [ "$#" -ge 2 ] || fail option-missing "--channel needs a value"; requested_channel=$2; shift 2 ;;
    --version) [ "$#" -ge 2 ] || fail option-missing "--version needs a value"; requested_version=$2; shift 2 ;;
    --install-dir) [ "$#" -ge 2 ] || fail option-missing "--install-dir needs a value"; install_root=$2; shift 2 ;;
    --cache-dir) [ "$#" -ge 2 ] || fail option-missing "--cache-dir needs a value"; cache_root=$2; shift 2 ;;
    --bin-dir) [ "$#" -ge 2 ] || fail option-missing "--bin-dir needs a value"; bin_dir=$2; shift 2 ;;
    --rollback) rollback=1; shift ;;
    --dry-run) dry_run=1; shift ;;
    --verbose) verbose=1; shift ;;
    --ci|--non-interactive) noninteractive=1; shift ;;
    --no-path|--yes) shift ;;
    -h|--help) usage; exit 0 ;;
    *) fail option-unknown "unknown option: $1" ;;
  esac
done

[ "$requested_channel" = "$channel" ] || fail channel-unavailable "this installer is pinned to $channel"
[ -z "$requested_version" ] || [ "$requested_version" = "$version" ] || fail version-unavailable "this installer selects exactly $version"

os=$(uname -s 2>/dev/null || true)
case "$os" in Darwin) platform=darwin ;; Linux) platform=linux ;; *) fail unsupported-platform "supported systems are macOS arm64 and glibc Linux x64" ;; esac
machine=$(uname -m 2>/dev/null || true)
case "$platform/$machine" in
  darwin/arm64|darwin/aarch64)
    architecture=arm64
    manifest_root='sha256:96e0a3f78bfa65a8ae06f4fd4bc035cc09211afad499ad6f905a380e1c49d2ae'
    artifact_root='sha256:09c1ac317ee471b803c0af86f0ec78d5296b572531eb393432c8485aa3e6bf14'
    release_cut_root='sha256:a755016042e1d724f888d6cb6bd3c6a4650debfe6d80c338c62b56a5783526f1'
    platform_slice_root='sha256:53cd8e37aaa0426223c1ff6444474c23a8d72eacb8e8789260123e60c199ecab'
    artifact_url='https://github.com/kungfu-systems/kungfu/releases/download/v4.0.0-alpha.2/kungfu-episodes-cli-darwin-arm64.tar.gz'
    artifact_size='145730301'
    artifact_digest='d5e71be871d8f88e317eded6634bf8717c7006fbc7b10ad93a944384ce6705a8'
    archive_name='kungfu-episodes-cli-darwin-arm64.tar.gz'
    archive_base='kungfu-episodes-cli-darwin-arm64'
    archive_entries='2684'
    archive_links='2'
    ;;
  linux/x86_64|linux/amd64)
    architecture=x64
    minimum_glibc='2.39'
    libc=$(getconf GNU_LIBC_VERSION 2>/dev/null || true)
    case "$libc" in glibc\ *) host_glibc=${libc#glibc } ;; *) fail unsupported-libc "the Alpha.2 Linux archive requires glibc $minimum_glibc or newer" ;; esac
    host_major=${host_glibc%%.*}; host_minor=${host_glibc#*.}; host_minor=${host_minor%%.*}
    required_major=${minimum_glibc%%.*}; required_minor=${minimum_glibc#*.}
    case "$host_major:$host_minor" in *[!0-9:]*|:|*:) fail unsupported-libc "could not determine the host glibc version" ;; esac
    if [ "$host_major" -lt "$required_major" ] || { [ "$host_major" -eq "$required_major" ] && [ "$host_minor" -lt "$required_minor" ]; }; then
      fail unsupported-libc "Alpha.2 requires glibc $minimum_glibc or newer; host reports $host_glibc"
    fi
    manifest_root='sha256:a81d194ebe7ea874753a66adaa1db6d56121c87cb6e3bf0ae7f6a97045d3a280'
    artifact_root='sha256:5df9536f89cd2a531aeca4b7857e6e32b8ae34c09ee7fcd24b8e5e19079119dd'
    release_cut_root='sha256:a755016042e1d724f888d6cb6bd3c6a4650debfe6d80c338c62b56a5783526f1'
    platform_slice_root='sha256:593235d04f85167548a9227b7aa37fd37805e0a9b38d63e3e4f467bde8a69996'
    artifact_url='https://github.com/kungfu-systems/kungfu/releases/download/v4.0.0-alpha.2/kungfu-episodes-cli-linux-x64.tar.gz'
    artifact_size='205955896'
    artifact_digest='78c8773ae5a33ae21d150b97af9ccbb3a11f8bfd4c740b83f99c04be519daeaa'
    archive_name='kungfu-episodes-cli-linux-x64.tar.gz'
    archive_base='kungfu-episodes-cli-linux-x64'
    archive_entries='5055'
    archive_links='1041'
    ;;
  darwin/*) fail unsupported-architecture "Alpha.2 supports Apple silicon, not $machine" ;;
  linux/*) fail unsupported-architecture "Alpha.2 supports Linux x64, not $machine" ;;
esac

version_key=$(printf '%s' "$manifest_root" | cut -c8-23)
version_root="$install_root/versions/$version-$version_key"
current_link="$install_root/current"
previous_link="$install_root/previous"
launcher="$bin_dir/kungfu"
stable_launcher="$current_link/install/kungfu-site-launcher"
receipt_line="catalog=$catalog_root version=$version source=$source_commit manifest=$manifest_root artifact=$artifact_root passport=$release_passport_root"
log "phase[plan]: $channel $version $platform/$architecture Cut $release_cut_root slice $platform_slice_root -> $version_root"
if [ "$rollback" -eq 1 ]; then log "phase[plan]: rollback current=$current_link previous=$previous_link"; fi
if [ "$dry_run" -eq 1 ]; then exit 0; fi

command -v readlink >/dev/null 2>&1 || fail prerequisite-missing "readlink is required"

owned_version_target() {
  case "$1" in "$install_root"/versions/*) return 0 ;; *) return 1 ;; esac
}

replace_pointer() {
  if [ "$platform" = darwin ]; then
    mv -fh "$1" "$2"
  else
    mv -fT "$1" "$2"
  fi
}

link_target() {
  link_value=$(readlink "$1" 2>/dev/null || true)
  case "$link_value" in
    /*) printf '%s\n' "$link_value" ;;
    '') printf '%s\n' '' ;;
    *) printf '%s/%s\n' "$(dirname "$1")" "$link_value" ;;
  esac
}

launcher_is_owned() {
  [ ! -e "$launcher" ] && [ ! -L "$launcher" ] && return 0
  [ -L "$launcher" ] || return 1
  launcher_target=$(link_target "$launcher")
  [ "$launcher_target" = "$stable_launcher" ] && return 0
  case "$launcher_target" in "$install_root"/versions/*/install/kungfu-archive-launcher) return 0 ;; *) return 1 ;; esac
}

launcher_is_owned || fail ownership-conflict "$launcher is not owned by the Kungfu managed installer"
existing=$(command -v kungfu 2>/dev/null || true)
[ -z "$existing" ] || [ "$existing" = "$launcher" ] || fail ownership-conflict "existing Kungfu is owned outside $launcher: $existing"

if [ "$rollback" -eq 1 ]; then
  [ -L "$current_link" ] || fail rollback-unavailable "no managed current version exists"
  [ -L "$previous_link" ] || fail rollback-unavailable "no verified previous version exists"
  current_target=$(link_target "$current_link")
  previous_target=$(link_target "$previous_link")
  owned_version_target "$current_target" || fail rollback-ownership "current points outside the managed versions directory"
  owned_version_target "$previous_target" || fail rollback-ownership "previous points outside the managed versions directory"
  previous_receipt="$previous_target/install/site-managed-receipt"
  previous_bootstrap_receipt="$previous_target/install/bootstrap-receipt.json"
  if [ ! -f "$previous_receipt" ] || ! grep -Eq '^catalog=sha256:[a-f0-9]{64} version=[^ ]+ source=[a-f0-9]{40} manifest=sha256:[a-f0-9]{64} artifact=sha256:[a-f0-9]{64} passport=sha256:[a-f0-9]{64}$' "$previous_receipt"; then
    fail rollback-verification "previous managed receipt is missing or invalid"
  fi
  if [ ! -f "$previous_bootstrap_receipt" ] || ! grep -Eq '"state"[[:space:]]*:[[:space:]]*"verified"' "$previous_bootstrap_receipt"; then
    fail rollback-verification "previous product bootstrap receipt is not verified"
  fi
  [ -x "$previous_target/kungfu" ] || fail rollback-verification "previous Kungfu runtime is missing"
  previous_version=$("$previous_target/kungfu" --version 2>/dev/null | sed -n '1p' || true)
  [ -n "$previous_version" ] || fail rollback-verification "previous Kungfu did not report a version"
  mkdir -p "$install_root" "$bin_dir"
  old_launcher_target=
  if [ -L "$launcher" ]; then old_launcher_target=$(link_target "$launcher"); fi
  restore_rollback() {
    restore_current="$install_root/.current.rollback-restore.$$"
    restore_previous="$install_root/.previous.rollback-restore.$$"
    ln -s "$current_target" "$restore_current"
    ln -s "$previous_target" "$restore_previous"
    replace_pointer "$restore_current" "$current_link" || true
    replace_pointer "$restore_previous" "$previous_link" || true
    if [ -n "$old_launcher_target" ]; then
      restore_launcher="$bin_dir/.kungfu.rollback-restore.$$"
      ln -s "$old_launcher_target" "$restore_launcher"
      replace_pointer "$restore_launcher" "$launcher" || true
    else
      rm -f "$launcher"
    fi
  }
  current_tmp="$install_root/.current.rollback.$$"
  previous_tmp="$install_root/.previous.rollback.$$"
  ln -s "$previous_target" "$current_tmp"
  ln -s "$current_target" "$previous_tmp"
  if ! replace_pointer "$current_tmp" "$current_link"; then
    rm -f "$current_tmp" "$previous_tmp"
    fail rollback-failed "could not activate the previous version"
  fi
  if ! replace_pointer "$previous_tmp" "$previous_link"; then
    restore_rollback
    fail rollback-failed "could not retain the displaced current version"
  fi
  launcher_tmp="$bin_dir/.kungfu.rollback.$$"
  ln -s "$stable_launcher" "$launcher_tmp"
  if ! replace_pointer "$launcher_tmp" "$launcher"; then
    restore_rollback
    fail rollback-failed "could not publish the rolled-back launcher"
  fi
  observed=$("$launcher" --version 2>/dev/null | sed -n '1p' || true)
  if [ "$observed" != "$previous_version" ]; then
    restore_rollback
    fail rollback-failed "rolled-back launcher did not report $previous_version; prior state was restored"
  fi
  log "rolled back: $launcher -> $previous_target ($previous_version)"
  exit 0
fi

managed_receipt="$version_root/install/site-managed-receipt"
if [ -f "$managed_receipt" ] && grep -Fqx "$receipt_line" "$managed_receipt" && [ -x "$version_root/kungfu" ]; then
  installed_version=$("$version_root/kungfu" --version 2>/dev/null | sed -n '1p' || true)
  current_target=$(link_target "$current_link")
  if [ "$installed_version" = "$version" ] && [ "$current_target" = "$version_root" ] && launcher_is_owned; then
    log "already installed: verified $version at $version_root"
    exit 0
  fi
fi

command -v curl >/dev/null 2>&1 || fail prerequisite-missing "curl is required"
command -v tar >/dev/null 2>&1 || fail prerequisite-missing "tar is required"
if command -v shasum >/dev/null 2>&1; then
  sha256_file() { shasum -a 256 "$1" | awk '{print $1}'; }
elif command -v sha256sum >/dev/null 2>&1; then
  sha256_file() { sha256sum "$1" | awk '{print $1}'; }
else
  fail prerequisite-missing "shasum or sha256sum is required"
fi

mkdir -p "$install_root/versions" "$bin_dir"
lock="$install_root/.managed-install.lock"
mkdir "$lock" 2>/dev/null || fail concurrent-install "another Kungfu installer owns $lock"
stage="$install_root/.managed-stage.$$"
cleanup() {
  [ ! -e "$stage" ] || rm -rf "$stage"
  rmdir "$lock" 2>/dev/null || true
}
trap cleanup EXIT HUP INT TERM
umask 077
mkdir "$stage" "$stage/download" "$stage/extract"

download() {
  download_url=$1
  destination=$2
  label=$3
  [ -e "$destination" ] || : > "$destination"
  attempt=1
  while [ "$attempt" -le 5 ]; do
    partial_bytes=$(wc -c < "$destination" 2>/dev/null | tr -d ' ' || printf '0')
    log "phase[download]: $label attempt $attempt/5, resume-byte $partial_bytes"
    progress_args='--silent --show-error'
    if [ "$noninteractive" -eq 0 ] && [ -t 2 ]; then progress_args='--progress-bar'; fi
    # shellcheck disable=SC2086
    if curl --fail --location --proto '=https' --tlsv1.2 --connect-timeout 20 \
      --continue-at - --output "$destination" $progress_args "$download_url"; then
      return 0
    fi
    [ "$attempt" -lt 5 ] || break
    case "$attempt" in 1) delay=1 ;; 2) delay=2 ;; 3) delay=4 ;; *) delay=8 ;; esac
    log "phase[retry]: $label failed; retrying in ${delay}s"
    sleep "$delay"
    attempt=$((attempt + 1))
  done
  fail download-failed "$label failed after 5 attempts; partial retained at $destination"
}

channel_file="$stage/download/channel.json"
download "$channel_url" "$channel_file" "signed channel"
observed_channel=$(sha256_file "$channel_file")
[ "$observed_channel" = "$channel_sha256" ] || fail channel-byte-mismatch "channel bytes differ from the reviewed signed channel"

cache_dir="$cache_root/sha256/$artifact_digest"
cache_file="$cache_dir/$archive_name"
partial_file="$cache_file.part"
mkdir -p "$cache_dir"
cache_valid=0
if [ -f "$cache_file" ]; then
  observed_size=$(wc -c < "$cache_file" | tr -d ' ')
  observed_digest=$(sha256_file "$cache_file")
  if [ "$observed_size" = "$artifact_size" ] && [ "$observed_digest" = "$artifact_digest" ]; then
    cache_valid=1
    log "phase[cache]: verified archive reused from $cache_file"
  else
    mv "$cache_file" "$cache_file.rejected.$$"
    log "phase[cache]: rejected unverified cache entry"
  fi
fi
if [ "$cache_valid" -eq 0 ]; then
  [ -e "$partial_file" ] || : > "$partial_file"
  download "$artifact_url" "$partial_file" "CLI archive"
  observed_size=$(wc -c < "$partial_file" | tr -d ' ')
  [ "$observed_size" = "$artifact_size" ] || fail artifact-size-mismatch "expected $artifact_size bytes, received $observed_size; partial retained at $partial_file"
  observed_digest=$(sha256_file "$partial_file")
  [ "$observed_digest" = "$artifact_digest" ] || fail artifact-digest-mismatch "archive digest differs; partial retained at $partial_file"
  mv "$partial_file" "$cache_file"
  log "phase[cache]: stored verified archive at $cache_file"
fi

log "phase[extract]: validating exact archive closure"
archive_list="$stage/archive.list"
tar -tzf "$cache_file" > "$archive_list" || fail archive-invalid "archive index could not be read"
observed_entries=$(wc -l < "$archive_list" | tr -d ' ')
[ "$observed_entries" = "$archive_entries" ] || fail archive-closure-mismatch "expected $archive_entries entries, observed $observed_entries"
awk -v root="$archive_base/" '
  index($0, root) != 1 || $0 ~ /^\// || $0 ~ /(^|\/)\.\.(\/|$)/ || $0 ~ /\\/ { exit 1 }
  END { if (NR == 0) exit 1 }
' "$archive_list" || fail archive-unsafe "archive paths escape the exact top-level directory"
archive_verbose="$stage/archive.verbose"
LC_ALL=C tar -tvzf "$cache_file" > "$archive_verbose" || fail archive-invalid "archive metadata could not be read"
archive_type_counts=$(awk '
  { type=substr($1,1,1); if (type=="l") links++; else if (type!="-" && type!="d") bad++ }
  END { printf "%d %d", links+0, bad+0 }
' "$archive_verbose") || fail archive-invalid "archive metadata could not be read"
observed_links=${archive_type_counts%% *}; bad_types=${archive_type_counts#* }
[ "$bad_types" = 0 ] || fail archive-unsafe "archive contains unsupported entry types"
[ "$observed_links" = "$archive_links" ] || fail archive-closure-mismatch "expected $archive_links reviewed links, observed $observed_links"
awk -v root="$archive_base" '
  function remains_inside(name, target, directory, combined, count, parts, stack, depth, index_, result) {
    if (target ~ /^\// || target ~ /\\/) return 0
    directory=name
    sub(/\/[^\/]*$/, "", directory)
    combined=directory "/" target
    count=split(combined, parts, "/")
    depth=0
    for (index_=1; index_<=count; index_++) {
      if (parts[index_] == "" || parts[index_] == ".") continue
      if (parts[index_] == "..") {
        if (depth == 0) return 0
        depth--
      } else {
        stack[++depth]=parts[index_]
      }
    }
    result=""
    for (index_=1; index_<=depth; index_++) result=result (index_ == 1 ? "" : "/") stack[index_]
    return result == root || index(result, root "/") == 1
  }
  substr($1,1,1) == "l" {
    marker=" " root "/"
    start=index($0, marker)
    if (start == 0) exit 1
    detail=substr($0, start + 1)
    arrow=index(detail, " -> ")
    if (arrow == 0) exit 1
    name=substr(detail, 1, arrow - 1)
    target=substr(detail, arrow + 4)
    if (!remains_inside(name, target)) exit 1
  }
' "$archive_verbose" || fail archive-unsafe "archive link target escapes the exact top-level directory"
tar -xzf "$cache_file" -C "$stage/extract" || fail archive-invalid "archive extraction failed"
candidate="$stage/extract/$archive_base"
[ -f "$candidate/product.json" ] || fail product-manifest-missing "product.json is missing"
[ -x "$candidate/runtime/kungfu" ] || fail runtime-missing "runtime/kungfu is missing"
platform_trust=signed-channel-digest
if [ "$platform" = darwin ]; then
  codesign --verify --deep --strict "$candidate/runtime/kungfu" >/dev/null 2>&1 || fail platform-trust-failed "macOS code signature did not verify"
  platform_trust=codesign-valid
fi

log "phase[verify]: running the Alpha.2 product bootstrap verifier"
mkdir -p "$candidate/install"
adapter_file="$candidate/install/alpha2-bootstrap-adapter.py"
cat > "$adapter_file" <<'KUNGFU_ALPHA2_BOOTSTRAP_ADAPTER'
# SPDX-License-Identifier: Apache-2.0
"""Exact Alpha.2 bridge for the bundled product bootstrap verifier.

The published Alpha.2 channel added two signed ``artifact.name`` fields after
the Alpha.2 CLI archives were built, while those archives also retain their
older combined product platform labels.  The bundled verifier rejects both
representations.  This adapter keeps the original bytes as authority, permits
only those exact field projections in the one reviewed channel root, and
delegates every trust and product check to the bundled
``verify_bootstrap_candidate`` implementation.
"""

from __future__ import annotations

import argparse
import copy
import hashlib
import json
from pathlib import Path
from typing import Any, Mapping

from kungfu import release_channel, runtime_upgrade


ADAPTER_SCHEMA = "kungfu.site-alpha2-bootstrap-adapter/v1"
ADAPTER_RECEIPT_SCHEMA = "kungfu.site-alpha2-bootstrap-adapter-receipt/v1"
CHANNEL_PAYLOAD_ROOT = (
    "sha256:8c031dd420e15ddde5b4e751cb4dcc3c0a2d4bd67956d295918e21165de6abdd"
)
SOURCE_COMMIT = "b0cff8236b8b3746f8028b9d519ed3b0e26096c9"
VERSION = "4.0.0-alpha.2"
ALLOWED_NAMES = {
    (
        "desktop",
        "Kungfu-Episodes-4.0.0-alpha.2-macos-arm64.zip",
        "https://github.com/kungfu-systems/kungfu/releases/download/"
        "v4.0.0-alpha.2/Kungfu-Episodes-4.0.0-alpha.2-macos-arm64.zip",
    ),
    (
        "cli",
        "kungfu-episodes-cli-darwin-arm64.tar.gz",
        "https://github.com/kungfu-systems/kungfu/releases/download/"
        "v4.0.0-alpha.2/kungfu-episodes-cli-darwin-arm64.tar.gz",
    ),
}
ALLOWED_PRODUCTS = {
    ("darwin-arm64", "kungfu-episodes-cli-darwin-arm64.tar.gz"): "darwin",
    ("linux-x64", "kungfu-episodes-cli-linux-x64.tar.gz"): "linux",
    ("windows-x64", "kungfu-episodes-cli-windows-x64.zip"): "win32",
}
SIGNED_MANIFEST_ROOTS = {
    ("darwin", "arm64"): (
        "sha256:96e0a3f78bfa65a8ae06f4fd4bc035cc09211afad499ad6f905a380e1c49d2ae"
    ),
    ("linux", "x64"): (
        "sha256:a81d194ebe7ea874753a66adaa1db6d56121c87cb6e3bf0ae7f6a97045d3a280"
    ),
    ("win32", "x64"): (
        "sha256:094448e272594dce2626fb9d4fe893e2608e700c1a86a5463f2bb3f4e2875551"
    ),
}
BUNDLED_IDENTITY_PROJECTIONS = {
    (
        "darwin",
        "arm64",
        "sha256:3f37f5469e1ebc95d2bb44ba46e259a7bc98e262d7b84f1a51c7fcb9bf79d53c",
    ): SIGNED_MANIFEST_ROOTS[("darwin", "arm64")],
}


class AdapterError(ValueError):
    pass


def canonical_json(value: Any) -> bytes:
    return json.dumps(
        value,
        sort_keys=True,
        separators=(",", ":"),
        ensure_ascii=True,
    ).encode("utf-8")


def content_root(value: Any) -> str:
    return f"sha256:{hashlib.sha256(canonical_json(value)).hexdigest()}"


def read_channel(path: Path) -> dict[str, Any]:
    payload = path.read_bytes()
    try:
        value = json.loads(payload.decode("utf-8"))
    except (UnicodeDecodeError, json.JSONDecodeError) as error:
        raise AdapterError("the Alpha.2 channel is not valid JSON") from error
    if not isinstance(value, dict):
        raise AdapterError("the Alpha.2 channel must be an object")
    if value.get("payloadRoot") != CHANNEL_PAYLOAD_ROOT:
        raise AdapterError("the channel is outside the exact Alpha.2 adapter boundary")
    if value.get("sourceCommit") != SOURCE_COMMIT:
        raise AdapterError("the channel source commit differs from Alpha.2")
    return value


def project_manifest(
    manifest: Mapping[str, Any],
    original_validate: Any,
) -> dict[str, Any]:
    value = copy.deepcopy(dict(manifest))
    if value.get("productVersion") != VERSION or value.get("sourceCommit") != SOURCE_COMMIT:
        return original_validate(value)

    removed: set[tuple[str, str, str]] = set()
    artifacts = value.get("artifacts")
    if not isinstance(artifacts, list):
        return original_validate(value)
    for artifact in artifacts:
        if not isinstance(artifact, dict) or "name" not in artifact:
            continue
        coordinate = (artifact.get("kind"), artifact.get("name"), artifact.get("url"))
        if value.get("platform") != "darwin" or value.get("architecture") != "arm64":
            raise AdapterError("artifact.name appeared outside the reviewed Darwin slice")
        if coordinate not in ALLOWED_NAMES:
            raise AdapterError("artifact.name differs from the reviewed Alpha.2 projection")
        removed.add(coordinate)
        del artifact["name"]
    if removed and removed != ALLOWED_NAMES:
        raise AdapterError("the Alpha.2 artifact.name projection is incomplete")
    return original_validate(value)


class CompatibilityJson:
    def __init__(self, delegate: Any) -> None:
        self.delegate = delegate
        self.projected_product = False

    def __getattr__(self, name: str) -> Any:
        return getattr(self.delegate, name)

    def loads(self, payload: Any, *args: Any, **kwargs: Any) -> Any:
        value = self.delegate.loads(payload, *args, **kwargs)
        if not isinstance(value, dict) or value.get("schema") != "kungfu.product.cli/v1":
            return value
        coordinate = (value.get("platform"), value.get("archive"))
        projected_platform = ALLOWED_PRODUCTS.get(coordinate)
        if (
            value.get("product") != "cli"
            or value.get("install", {}).get("source") != "archive"
            or projected_platform is None
        ):
            raise AdapterError("product.json differs from the reviewed Alpha.2 projection")
        projected = copy.deepcopy(value)
        projected["platform"] = projected_platform
        self.projected_product = True
        return projected


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument("channel_index", type=Path)
    parser.add_argument("candidate_archive", type=Path)
    parser.add_argument("candidate_root", type=Path)
    parser.add_argument("--channel", required=True)
    parser.add_argument("--platform", required=True, dest="platform_name")
    parser.add_argument("--architecture", required=True)
    parser.add_argument("--version", required=True)
    parser.add_argument("--manifest-root", required=True)
    parser.add_argument("--artifact-root", required=True)
    parser.add_argument("--platform-trust", required=True)
    parser.add_argument("--trusted-key", required=True, action="append")
    parser.add_argument("--adapter-receipt", required=True, type=Path)
    return parser.parse_args()


def main() -> int:
    args = parse_args()
    channel = read_channel(args.channel_index)
    if args.version != VERSION or args.channel != "alpha":
        raise AdapterError("the adapter only accepts the exact Alpha.2 alpha channel")
    trusted_keys: dict[str, str] = {}
    for item in args.trusted_key:
        key_id, separator, public_key = item.partition("=")
        if not separator or not key_id or not public_key or key_id in trusted_keys:
            raise AdapterError("trusted key coordinates are invalid")
        trusted_keys[key_id] = public_key

    signed_manifests: dict[tuple[str, str], dict[str, Any]] = {}
    for entry in channel.get("entries", []):
        if not isinstance(entry, dict) or not isinstance(entry.get("manifest"), dict):
            raise AdapterError("the Alpha.2 channel entries are malformed")
        coordinate = (entry.get("platform"), entry.get("architecture"))
        expected_root = SIGNED_MANIFEST_ROOTS.get(coordinate)
        if expected_root is None or entry.get("manifestRoot") != expected_root:
            raise AdapterError("the Alpha.2 signed manifest roots differ from the adapter")
        signed_manifests[coordinate] = entry["manifest"]
    if set(signed_manifests) != set(SIGNED_MANIFEST_ROOTS):
        raise AdapterError("the Alpha.2 signed target closure differs from the adapter")

    original_validate = runtime_upgrade.validate_manifest
    original_release_json = release_channel.json
    compatibility_json = CompatibilityJson(original_release_json)
    projected_bundled_identity = False

    def exact_alpha2_validate(manifest: Mapping[str, Any]) -> dict[str, Any]:
        nonlocal projected_bundled_identity
        bundled_coordinate = (
            manifest.get("platform"),
            manifest.get("architecture"),
            content_root(manifest),
        )
        signed_root = BUNDLED_IDENTITY_PROJECTIONS.get(bundled_coordinate)
        if signed_root is not None:
            coordinate = bundled_coordinate[:2]
            signed_manifest = signed_manifests[coordinate]
            if content_root(signed_manifest) != signed_root:
                raise AdapterError("the signed Alpha.2 identity projection root differs")
            projected_bundled_identity = True
            return project_manifest(signed_manifest, original_validate)
        return project_manifest(manifest, original_validate)

    runtime_upgrade.validate_manifest = exact_alpha2_validate
    release_channel.json = compatibility_json
    try:
        receipt = release_channel.verify_bootstrap_candidate(
            channel_index=args.channel_index,
            trusted_keys=trusted_keys,
            candidate_archive=args.candidate_archive,
            candidate_root=args.candidate_root,
            channel=args.channel,
            platform_name=args.platform_name,
            architecture=args.architecture,
            version=args.version,
            manifest_root=args.manifest_root,
            artifact_root=args.artifact_root,
            platform_trust=args.platform_trust,
        )
    finally:
        runtime_upgrade.validate_manifest = original_validate
        release_channel.json = original_release_json
    if not compatibility_json.projected_product:
        raise AdapterError("the expected Alpha.2 product platform projection was not used")

    adapter_digest = f"sha256:{hashlib.sha256(Path(__file__).read_bytes()).hexdigest()}"
    adapter_receipt = {
        "schema": ADAPTER_RECEIPT_SCHEMA,
        "state": "verified",
        "adapter": {"schema": ADAPTER_SCHEMA, "digest": adapter_digest},
        "compatibilityMode": "signed-alpha2-field-projection",
        "bundledIdentityProjection": projected_bundled_identity,
        "channelPayloadRoot": channel["payloadRoot"],
        "manifestRoot": args.manifest_root,
        "nativeReceiptRoot": receipt["receiptRoot"],
        "platform": args.platform_name,
        "architecture": args.architecture,
        "productVersion": args.version,
    }
    adapter_receipt["receiptRoot"] = content_root(adapter_receipt)
    args.adapter_receipt.write_text(
        json.dumps(adapter_receipt, indent=2, sort_keys=True) + "\n",
        encoding="utf-8",
    )
    print(json.dumps(receipt, indent=2, sort_keys=True))
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except (AdapterError, OSError, release_channel.ReleaseChannelError) as error:
        raise SystemExit(f"alpha2-bootstrap-adapter: {error}") from error
KUNGFU_ALPHA2_BOOTSTRAP_ADAPTER
observed_adapter=$(sha256_file "$adapter_file")
[ "$observed_adapter" = '4e91a89ec7ffc3f38cf9af6fa38ade062c158d627ca40b04400317948a0ccace' ] || fail product-verification-failed "embedded Alpha.2 compatibility adapter digest differs from the catalog"
candidate_python="$candidate/runtime/python/bin/python3"
[ -x "$candidate_python" ] || fail product-verification-failed "candidate embedded Python is unavailable"
KUNGFU_INSTALL_SOURCE=site-managed-archive \
KUNGFU_DIR="$candidate/runtime" \
KUNGFU_PRODUCT_MANIFEST="$candidate/product.json" \
KUNGFU_UPGRADE_MANIFEST="$candidate/upgrade/kungfu-release-manifest.json" \
"$candidate_python" "$adapter_file" "$channel_file" "$cache_file" "$candidate" \
  --channel "$channel" --platform "$platform" --architecture "$architecture" \
  --version "$version" --manifest-root "$manifest_root" --artifact-root "$artifact_root" \
  --platform-trust "$platform_trust" --trusted-key "$trusted_key" \
  --adapter-receipt "$candidate/install/alpha2-bootstrap-adapter-receipt.json" \
  > "$candidate/install/bootstrap-receipt.json" || fail product-verification-failed "staged Kungfu rejected the signed release identity"
candidate_version=$("$candidate/kungfu" --version 2>/dev/null | sed -n '1p' || true)
[ "$candidate_version" = "$version" ] || fail product-version-mismatch "staged Kungfu reported '$candidate_version'"
printf '%s\n' "$receipt_line" > "$candidate/install/site-managed-receipt"
cat > "$candidate/install/kungfu-site-launcher" <<'KUNGFU_SITE_LAUNCHER'
#!/bin/sh
set -eu
target=$0
while [ -L "$target" ]; do
  link=$(readlink "$target")
  case "$link" in /*) target=$link ;; *) target=$(dirname "$target")/$link ;; esac
done
version_root=$(CDPATH= cd -- "$(dirname "$target")/.." && pwd)
export KUNGFU_INSTALL_SOURCE=site-managed-archive
export KUNGFU_DIR="$version_root/runtime"
exec "$version_root/kungfu" "$@"
KUNGFU_SITE_LAUNCHER
chmod 755 "$candidate/install/kungfu-site-launcher"

if [ -d "$version_root" ]; then
  if [ ! -f "$managed_receipt" ] || ! grep -Fqx "$receipt_line" "$managed_receipt"; then
    fail installed-content-conflict "$version_root exists without the exact managed receipt"
  fi
  rm -rf "$candidate"
  log "phase[publish]: verified installed content reused"
else
  mv "$candidate" "$version_root" || fail publish-failed "could not publish the verified version"
  log "phase[publish]: installed complete archive closure at $version_root"
fi

old_current=
if [ -L "$current_link" ]; then
  old_current=$(link_target "$current_link")
  owned_version_target "$old_current" || fail activation-ownership "current points outside the managed versions directory"
elif [ -e "$current_link" ]; then
  fail activation-ownership "$current_link is not a managed symbolic link"
fi
if [ -L "$previous_link" ]; then
  owned_version_target "$(link_target "$previous_link")" || fail activation-ownership "previous points outside the managed versions directory"
elif [ -e "$previous_link" ]; then
  fail activation-ownership "$previous_link is not a managed symbolic link"
fi

old_launcher_target=
if [ -L "$launcher" ]; then old_launcher_target=$(link_target "$launcher"); fi
restore_activation() {
  if [ -n "$old_current" ]; then
    restore_current="$install_root/.current.restore.$$"
    ln -s "$old_current" "$restore_current"
    replace_pointer "$restore_current" "$current_link" || true
  else
    rm -f "$current_link"
  fi
  if [ -n "$old_launcher_target" ]; then
    restore_launcher="$bin_dir/.kungfu.restore.$$"
    ln -s "$old_launcher_target" "$restore_launcher"
    replace_pointer "$restore_launcher" "$launcher" || true
  else
    rm -f "$launcher"
  fi
}

launcher_tmp="$bin_dir/.kungfu.managed.$$"
ln -s "$stable_launcher" "$launcher_tmp"
current_tmp="$install_root/.current.managed.$$"
ln -s "$version_root" "$current_tmp"
if ! replace_pointer "$current_tmp" "$current_link"; then
  rm -f "$current_tmp" "$launcher_tmp"
  fail activation-failed "could not atomically activate $version"
fi
if ! replace_pointer "$launcher_tmp" "$launcher"; then
  restore_activation
  fail activation-failed "could not publish the managed launcher; prior current was restored"
fi
if ! observed=$("$launcher" --version 2>/dev/null | sed -n '1p') || [ "$observed" != "$version" ]; then
  restore_activation
  fail activation-verification-failed "activated launcher did not report $version; prior current was restored"
fi
if [ -n "$old_current" ] && [ "$old_current" != "$version_root" ]; then
  previous_tmp="$install_root/.previous.managed.$$"
  ln -s "$old_current" "$previous_tmp"
  if ! replace_pointer "$previous_tmp" "$previous_link"; then
    restore_activation
    fail activation-failed "previous coordinate could not be recorded; prior current was restored"
  fi
fi

trap - EXIT HUP INT TERM
cleanup
log "installed: $launcher -> $version_root"
log "PATH was not modified; cache=$cache_file current=$current_link previous=$previous_link"
