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

channel='alpha'
version='4.0.0-alpha.3'
source_commit='6d99af738b78eccb48885a5fd59b88a0e5e4900a'
channel_url='https://kungfu.tech/channels/alpha/af360a051e2201d006e2c8f75627fc575f981e00c4f4cc998c90e130d9a40b5b/index.json'
channel_sha256='2234799d7cc054f0c2a7009a4278cf45e2938761a3b66b9d850520ec155cabb3'
trusted_key='ed25519-3c473c24ca261745=bNB6syHpgY0RKMHPKUhekyQupwgvtwqQ6qqrUV2ecfQ='
catalog_root='sha256:d4cc77e8917ba04721d494ca7f717a8554892dd85c9fde94fbbc5266e5d1bf8f'
release_passport_root='sha256:445c0309e39b1db38637b9478fed01040dc7a08b3c8a3d4881cba0904563ecbd'
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 ;; *) platform=linux ;; esac
case "$platform" in
  darwin)
    architecture=arm64
    manifest_root='sha256:485e5421107a8611b743c2aa325d021a63d410baef408997a61e4488e5f6e8bf'
    artifact_root='sha256:a3ab9ebd0cf905585ad279634cc89e462d73bb11879ebbab40471eb2ca7e6e55'
    release_cut_root='sha256:80640129776ab0a5b11c4e0d66d6158fd6e05613c67ad790a00b29fe65ffca38'
    platform_slice_root='sha256:10e9c078de400f05f69bcf408a7ff65ab197f5fad84fa17d67ad04437920f017'
    artifact_url='https://github.com/kungfu-systems/kungfu/releases/download/v4.0.0-alpha.3/kungfu-episodes-cli-darwin-arm64.tar.gz'
    artifact_size='147567775'
    artifact_digest='be64a25a8756e03dfd1c3b59374dac781cd50eea645ed09a691c398de42403af'
    archive_name='kungfu-episodes-cli-darwin-arm64.tar.gz'
    archive_base='kungfu-episodes-cli-darwin-arm64'
    archive_entries='2895'
    archive_links='2'
    ;;
  linux)
    architecture=x64
    manifest_root='sha256:6d8d25473e4be07fea4373703dfb6db8d1c4d0406e6955282d0a101d8ec430e8'
    artifact_root='sha256:906ef9c7c65c739e78f3f3dedc0accaf0da98331a7c92213d5ee3741e9779490'
    release_cut_root='sha256:80640129776ab0a5b11c4e0d66d6158fd6e05613c67ad790a00b29fe65ffca38'
    platform_slice_root='sha256:5d879af852068de8b6d45cf1c6158b93256593a3c5931dc8c809ad752a0eff93'
    artifact_url='https://github.com/kungfu-systems/kungfu/releases/download/v4.0.0-alpha.3/kungfu-episodes-cli-linux-x64.tar.gz'
    artifact_size='208214214'
    artifact_digest='c7ede1fc9692a25a6ebefd32cac75e9fcaa5c7717d3568a599695ebc63239d49'
    archive_name='kungfu-episodes-cli-linux-x64.tar.gz'
    archive_base='kungfu-episodes-cli-linux-x64'
    archive_entries='5226'
    archive_links='1041'
    ;;
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_site_managed() {
  [ -L "$launcher" ] || return 1
  launcher_target=$(link_target "$launcher")
  [ "$launcher_target" = "$stable_launcher" ]
}

ensure_default_path() {
  case ":$PATH:" in *":$bin_dir:"*) return 0 ;;
  esac
  case "${SHELL##*/}" in
    zsh) profile="$HOME/.zprofile" ;;
    bash) profile="$HOME/.bashrc" ;;
    *) profile="$HOME/.profile" ;;
  esac
  if [ "$bin_dir" != "$HOME/.local/bin" ]; then
    log "path: installed at $bin_dir; add it to PATH to use this custom location in new shells"
    return 0
  fi
  marker='# kungfu-site-managed PATH'
  if [ -f "$profile" ] && grep -Fq "$marker" "$profile"; then return 0; fi
  if {
    printf '\n%s\n' "$marker"
    printf 'export PATH="$HOME/.local/bin:$PATH"\n'
  } >> "$profile" 2>/dev/null; then
    log "path: added $bin_dir to $profile for future shells"
  else
    log "path: installation succeeded, but could not update $profile; add $bin_dir to PATH manually"
  fi
}

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_site_managed; then
    ensure_default_path
    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.3 product bootstrap verifier"
mkdir -p "$candidate/install"
adapter_file="$candidate/install/alpha3-bootstrap-adapter.py"
cat > "$adapter_file" <<'KUNGFU_ALPHA3_BOOTSTRAP_ADAPTER'
# SPDX-License-Identifier: Apache-2.0
"""Exact Alpha.3 identity bridge for the bundled product bootstrap verifier.

The published Alpha.3 CLI archives retain combined product platform labels
(``darwin-arm64``, ``linux-x64``, and ``windows-x64``), while the signed
channel identifies the same targets by platform and architecture.  The
bundled verifier compares those representations directly and rejects the
otherwise authentic archive.  The bundled release manifests also retain
reviewed pre-channel roots. This adapter keeps the original bytes as authority,
projects only those exact product and release-identity values in the signed
channel closure, 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

from kungfu import release_channel, runtime_upgrade


ADAPTER_SCHEMA = "kungfu.site-alpha3-bootstrap-adapter/v1"
ADAPTER_RECEIPT_SCHEMA = "kungfu.site-alpha3-bootstrap-adapter-receipt/v1"
CHANNEL_PAYLOAD_ROOT = (
    "sha256:af360a051e2201d006e2c8f75627fc575f981e00c4f4cc998c90e130d9a40b5b"
)
SOURCE_COMMIT = "6d99af738b78eccb48885a5fd59b88a0e5e4900a"
VERSION = "4.0.0-alpha.3"
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:485e5421107a8611b743c2aa325d021a63d410baef408997a61e4488e5f6e8bf"
    ),
    ("linux", "arm64"): (
        "sha256:3fedc3677729e056dafdffe4292c85f7b04069be5fd98d56220eb9a090fcc3c7"
    ),
    ("linux", "x64"): (
        "sha256:6d8d25473e4be07fea4373703dfb6db8d1c4d0406e6955282d0a101d8ec430e8"
    ),
    ("win32", "x64"): (
        "sha256:0f83d080f2480d9dc4b0888c9c9818bb61c0736f7b3c15b00f7a8f7603ab5dc7"
    ),
}
BUNDLED_IDENTITY_PROJECTIONS = {
    (
        "darwin",
        "arm64",
        "sha256:e53f57f6118b2e3d12350e81a827c616ce40fe7aaaca87ede1d0ad1243019e21",
    ): SIGNED_MANIFEST_ROOTS[("darwin", "arm64")],
    (
        "linux",
        "x64",
        "sha256:c7e2faa5d7912c744949e38efa75d8bccb76ab5ecddfc54cd7249d856717b451",
    ): SIGNED_MANIFEST_ROOTS[("linux", "x64")],
    (
        "win32",
        "x64",
        "sha256:478f7daf9e741d25996c6c7bee8fb341aece27989f60929bcf2dad21e463e1b4",
    ): SIGNED_MANIFEST_ROOTS[("win32", "x64")],
}


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.3 channel is not valid JSON") from error
    if not isinstance(value, dict):
        raise AdapterError("the Alpha.3 channel must be an object")
    if value.get("payloadRoot") != CHANNEL_PAYLOAD_ROOT:
        raise AdapterError("the channel is outside the exact Alpha.3 adapter boundary")
    if value.get("sourceCommit") != SOURCE_COMMIT:
        raise AdapterError("the channel source commit differs from Alpha.3")
    return 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.3 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.3 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.3 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.3 signed manifest roots differ from the adapter")
        signed_manifests[coordinate] = entry["manifest"]
    if set(signed_manifests) != set(SIGNED_MANIFEST_ROOTS):
        raise AdapterError("the Alpha.3 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_alpha3_validate(manifest: dict[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 None:
            return original_validate(manifest)
        coordinate = bundled_coordinate[:2]
        signed_manifest = signed_manifests[coordinate]
        if content_root(signed_manifest) != signed_root:
            raise AdapterError("the signed Alpha.3 identity projection root differs")
        projected_bundled_identity = True
        return original_validate(signed_manifest)

    runtime_upgrade.validate_manifest = exact_alpha3_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.3 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-alpha3-identity-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"alpha3-bootstrap-adapter: {error}") from error
KUNGFU_ALPHA3_BOOTSTRAP_ADAPTER
observed_adapter=$(sha256_file "$adapter_file")
[ "$observed_adapter" = '69ff436d497cecb2d948b236958a03eb197ddfe19150dbd71ba968e70608a0dc' ] || fail product-verification-failed "embedded Alpha.3 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/alpha3-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
    displaced_version_root="$version_root.legacy.$$"
    mv "$version_root" "$displaced_version_root" || fail publish-failed "could not preserve pre-existing content at $version_root"
    if ! mv "$candidate" "$version_root"; then
      mv "$displaced_version_root" "$version_root" || true
      fail publish-failed "could not publish verified content at $version_root"
    fi
    log "phase[publish]: preserved legacy content at $displaced_version_root and installed verified Alpha.3 content"
  else
    rm -rf "$candidate"
    log "phase[publish]: verified installed content reused"
  fi
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" || old_current=
fi
if [ -L "$previous_link" ]; then
  owned_version_target "$(link_target "$previous_link")" || true
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"
ensure_default_path
log "cache=$cache_file current=$current_link previous=$previous_link"
