#!/bin/sh
set -eu

# Rendered into the public release by build_release_artifacts.py.
version="0.0.12"
linux_x86_64_sha256="3f217e2e805854cdf3c15e6c782b1438f06566fd89eeca17d6259da8d4b2b200"
macos_arm64_sha256="b54a04d24699650585e4c319aa49f40dbe69b9fad5ea880e6c961ff1bb371319"
macos_x86_64_sha256="c05893d16d170d5228b77a98e835ed176e3690d52cbdedf850f5f4282300885f"
release_origin="https://downloads.mesh.skilak.ai/releases/v${version}"
asset_origin=""
download_query=""
if [ "${SKILAK_INTERNAL:-0}" = "1" ]; then
  download_query="?internal=1"
fi
source_repository="SkilakLabs/mesh"
source_dir=""
source_commit=""
source_ref="refs/tags/v${version}"
source_ref_explicit=0
trusted_root=""
activate_only=0
modify_path=1
verbose=0
install_prefix=""
bin_dir=""

usage() {
  cat <<'USAGE'
Usage: install.sh [options]

Install the container-free Skilak Mesh command-line tool on Linux or macOS.

Options:
  --source-dir DIR  Install from a directory containing the native archive,
                    checksum manifest, and Sigstore provenance bundle.
  --source-commit SHA
                    Reviewed 40-character source commit supplied independently
                    of the release assets (required with --source-dir).
  --source-ref REF  Exact release tag identity that produced the provenance
                    bundle (default: refs/tags/vVERSION).
  --trusted-root FILE
                    GitHub/Sigstore trusted-root JSONL obtained independently;
                    required with --source-dir for offline verification.
  --prefix DIR      Versioned program root (Linux only; platform default when
                    omitted). macOS uses its canonical Program directory.
  --bin-dir DIR     Directory for the `smesh` launcher (default: ~/.local/bin).
  --no-modify-path  Leave shell startup files unchanged; print a manual PATH line.
  --confirm-path    Accepted for compatibility; no effect.
  --verbose         Show installation and service details.
  --activate-only   Point the launcher at an already installed version.
  --help            Show this help.
USAGE
}

while [ "$#" -gt 0 ]; do
  case "$1" in
    --source-dir)
      [ "$#" -ge 2 ] || { echo "install.sh: --source-dir needs a value" >&2; exit 2; }
      source_dir=$2
      shift 2
      ;;
    --source-commit)
      [ "$#" -ge 2 ] || { echo "install.sh: --source-commit needs a value" >&2; exit 2; }
      source_commit=$2
      shift 2
      ;;
    --source-ref)
      [ "$#" -ge 2 ] || { echo "install.sh: --source-ref needs a value" >&2; exit 2; }
      source_ref=$2
      source_ref_explicit=1
      shift 2
      ;;
    --trusted-root)
      [ "$#" -ge 2 ] || { echo "install.sh: --trusted-root needs a value" >&2; exit 2; }
      trusted_root=$2
      shift 2
      ;;
    --prefix)
      [ "$#" -ge 2 ] || { echo "install.sh: --prefix needs a value" >&2; exit 2; }
      install_prefix=$2
      shift 2
      ;;
    --bin-dir)
      [ "$#" -ge 2 ] || { echo "install.sh: --bin-dir needs a value" >&2; exit 2; }
      bin_dir=$2
      shift 2
      ;;
    --confirm-path)
      :
      shift
      ;;
    --no-modify-path)
      modify_path=0
      shift
      ;;
    --verbose)
      verbose=1
      shift
      ;;
    --activate-only)
      activate_only=1
      shift
      ;;
    --help|-h)
      usage
      exit 0
      ;;
    *)
      echo "install.sh: unknown option: $1" >&2
      usage >&2
      exit 2
      ;;
  esac
done

safe_version_component() {
  case "$1" in
    ''|*[!0-9.]*|.*|*.|*..*) return 1 ;;
  esac
  return 0
}

if ! safe_version_component "$version"; then
    echo "install.sh: invalid rendered version: $version" >&2
    exit 1
fi

platform_name=""
architecture=""
archive_type=""
service_name=""
case "$(uname -s 2>/dev/null || true):$(uname -m 2>/dev/null || true)" in
  Linux:x86_64)
    platform_name="Linux"
    architecture="x86_64"
    archive_type="tar"
    service_name="com.skilak.mesh.gateway.service"
    archive_name="skilakmesh-${version}-linux-x86_64.tar.gz"
    record_name="skilakmesh-${version}-linux-x86_64.build.json"
    checksums_name="SHA256SUMS.linux"
    provenance_name="SHA256SUMS.linux.sigstore.json"
    expected_archive_sha256="$linux_x86_64_sha256"
    asset_origin="${release_origin}/native/linux-x86_64"
    ;;
  Darwin:arm64)
    platform_name="macOS"
    architecture="arm64"
    archive_type="zip"
    service_name="com.skilak.mesh.gateway"
    archive_name="skilakmesh-${version}-macos-arm64-cli.zip"
    record_name="skilakmesh-${version}-macos-arm64-cli.build.json"
    checksums_name="SHA256SUMS.macos"
    provenance_name="SHA256SUMS.macos.sigstore.json"
    expected_archive_sha256="$macos_arm64_sha256"
    asset_origin="${release_origin}/native/macos-arm64"
    ;;
  Darwin:x86_64)
    platform_name="macOS"
    architecture="x86_64"
    archive_type="zip"
    service_name="com.skilak.mesh.gateway"
    archive_name="skilakmesh-${version}-macos-x86_64-cli.zip"
    record_name="skilakmesh-${version}-macos-x86_64-cli.build.json"
    checksums_name="SHA256SUMS.macos"
    provenance_name="SHA256SUMS.macos.sigstore.json"
    expected_archive_sha256="$macos_x86_64_sha256"
    asset_origin="${release_origin}/native/macos-x86_64"
    ;;
  *)
    echo "install.sh: supported platforms are Linux x86_64 and macOS arm64/x86_64" >&2
    exit 1
    ;;
esac

for account_tool in awk id; do
  command -v "$account_tool" >/dev/null 2>&1 || {
    echo "install.sh: ${account_tool} is required for account validation" >&2
    exit 1
  }
done
account_uid=$(id -u) || {
  echo "install.sh: current account could not be identified" >&2
  exit 1
}
case "$account_uid" in
  ''|*[!0-9]*)
    echo "install.sh: current account identifier is invalid" >&2
    exit 1
    ;;
esac
if [ "$platform_name" = "Linux" ]; then
  command -v getent >/dev/null 2>&1 || {
    echo "install.sh: getent is required to resolve the Linux account home" >&2
    exit 1
  }
  account_home=$(getent passwd "$account_uid" | awk -F: -v uid="$account_uid" '
    NR == 1 && NF == 7 && "x" $3 == "x" uid { home = $6; matches = 1 }
    END {
      if (NR != 1 || matches != 1 || home == "") exit 1
      print home
    }
  ') || {
    echo "install.sh: Linux account home could not be resolved exactly" >&2
    exit 1
  }
else
  command -v dscacheutil >/dev/null 2>&1 || {
    echo "install.sh: dscacheutil is required to resolve the macOS account home" >&2
    exit 1
  }
  account_home=$(dscacheutil -q user -a uid "$account_uid" | \
    awk -v uid="$account_uid" '
      $1 == "uid:" && NF == 2 && "x" $2 == "x" uid {
        uid_matches++
      }
      $1 == "dir:" {
        value = $0
        sub(/^dir:[[:space:]]*/, "", value)
        if (value != "") {
          home = value
          home_matches++
        }
      }
      END {
        if (uid_matches != 1 || home_matches != 1) exit 1
        print home
      }
    ') || {
    echo "install.sh: macOS account home could not be resolved exactly" >&2
    exit 1
  }
fi
case "$account_home" in
  ''|/|/*/../*|*/..|/*/./*|*/.|*//*)
    echo "install.sh: account database returned an unsafe home directory" >&2
    exit 1
    ;;
  /*) ;;
  *)
    echo "install.sh: account database returned an unsafe home directory" >&2
    exit 1
    ;;
esac
if [ "${HOME:-}" != "$account_home" ]; then
  echo "install.sh: HOME differs from the account database; restore HOME to ${account_home} and retry" >&2
  exit 1
fi

if [ -z "$install_prefix" ]; then
  if [ "$platform_name" = "Linux" ]; then
    install_prefix="${account_home}/.local/share/skilakmesh/native"
  else
    install_prefix="${account_home}/Library/Application Support/SkilakMesh/Program"
  fi
fi
if [ -z "$bin_dir" ]; then
  bin_dir="${account_home}/.local/bin"
fi

if [ "$platform_name" = "macOS" ] && \
    [ "$install_prefix" != "${account_home}/Library/Application Support/SkilakMesh/Program" ]; then
  echo "install.sh: macOS requires the canonical per-user Program directory" >&2
  exit 1
fi

version_root="${install_prefix}/versions/${version}"
launcher="${bin_dir}/smesh"
receipt="${install_prefix}/install-receipt.json"

case "$install_prefix" in
  ''|/|/*/../*|*/..|/*/./*|*/.|*//*)
    echo "install.sh: refusing unsafe installation prefix: ${install_prefix}" >&2
    exit 1
    ;;
  /*) ;;
  *)
    echo "install.sh: refusing unsafe installation prefix: ${install_prefix}" >&2
    exit 1
    ;;
esac
case "$bin_dir" in
  ''|/|/*/../*|*/..|/*/./*|*/.|*//*)
    echo "install.sh: refusing unsafe launcher directory: ${bin_dir}" >&2
    exit 1
    ;;
  /*) ;;
  *)
    echo "install.sh: refusing unsafe launcher directory: ${bin_dir}" >&2
    exit 1
    ;;
esac

path_chain_is_safe() {
  inspected=$1
  current_uid=$(id -u) || return 1
  current=$inspected
  while :; do
    if [ -L "$current" ]; then
      return 1
    fi
    if [ -e "$current" ]; then
      [ -d "$current" ] || return 1
      details=$(LC_ALL=C stat -c '%u %a' "$current" 2>/dev/null || \
        LC_ALL=C stat -f '%u %Op' "$current" 2>/dev/null) || return 1
      printf '%s\n' "$details" | awk -v uid="$current_uid" '
        NF == 2 && $1 ~ /^[0-9]+$/ && $2 ~ /^[0-9]+$/ {
          owner = $1 + 0
          mode = $2 + 0
          sticky_digit = int(mode / 1000) % 10
          group_digit = int(mode / 10) % 10
          other_digit = mode % 10
          writable = (group_digit == 2 || group_digit == 3 || group_digit == 6 || group_digit == 7 || other_digit == 2 || other_digit == 3 || other_digit == 6 || other_digit == 7)
          if ((owner == 0 || owner == uid) && (!writable || (owner == 0 && sticky_digit % 2 == 1))) exit 0
        }
        { exit 1 }
      ' || return 1
    fi
    [ "$current" = "/" ] && break
    current=${current%/*}
    [ -n "$current" ] || current=/
  done
  return 0
}

for path_tool in awk id stat; do
  command -v "$path_tool" >/dev/null 2>&1 || {
    echo "install.sh: ${path_tool} is required for path validation" >&2
    exit 1
  }
done
path_chain_is_safe "$install_prefix" || {
  echo "install.sh: installation prefix has an unsafe owner, mode, or symlink" >&2
  exit 1
}
path_chain_is_safe "$bin_dir" || {
  echo "install.sh: launcher directory has an unsafe owner, mode, or symlink" >&2
  exit 1
}
configured_install=0
config_root="${account_home}/.config/skilakmesh"
if path_chain_is_safe "$config_root" && [ -f "${config_root}/config.json" ] && \
    [ ! -L "${config_root}/config.json" ]; then
  configured_install=1
fi
previous_version=""
case "$bin_dir" in
  *:*|*"
"*)
    echo "install.sh: launcher directory cannot contain a PATH separator" >&2
    exit 1
    ;;
esac

path_has_bin=0
old_ifs=$IFS
IFS=:
set -f
for path_entry in ${PATH:-}; do
  if [ "$path_entry" = "$bin_dir" ]; then
    path_has_bin=1
    break
  fi
done
set +f
IFS=$old_ifs
# Quote even custom paths as shell data, never as executable shell syntax.
shell_quote() {
  printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"
}
path_export_line() {
  if [ "$bin_dir" = "${account_home}/.local/bin" ]; then
    printf '%s\n' 'export PATH="$HOME/.local/bin:$PATH"'
  else
    printf 'export PATH=%s:"$PATH"\n' "$(shell_quote "$bin_dir")"
  fi
}
path_profile=""
case "${SHELL:-}" in
  */zsh|zsh) path_profile="${account_home}/.zprofile" ;;
  */bash|bash)
    if [ "$platform_name" = "macOS" ]; then
      path_profile="${account_home}/.bash_profile"
    else
      path_profile="${account_home}/.bashrc"
    fi
    ;;
  *) path_profile="${account_home}/.profile" ;;
esac

profile_is_safe() {
  path_chain_is_safe "$account_home" || return 1
  [ ! -L "$path_profile" ] || return 1
  [ -e "$path_profile" ] || return 0
  [ -f "$path_profile" ] || return 1
  details=$(LC_ALL=C stat -c '%u %a %h' "$path_profile" 2>/dev/null || \
    LC_ALL=C stat -f '%u %Op %l' "$path_profile" 2>/dev/null) || return 1
  printf '%s\n' "$details" | awk -v uid="$account_uid" '
    NF == 3 && $1 == uid && $3 == 1 {
      group = int($2 / 10) % 10; other = $2 % 10
      if (group != 2 && group != 3 && group != 6 && group != 7 &&
          other != 2 && other != 3 && other != 6 && other != 7) exit 0
    }
    { exit 1 }
  '
}
modify_shell_path() {
  [ "$path_has_bin" -eq 0 ] && [ "$modify_path" -eq 1 ] || return 0
  profile_is_safe || {
    echo "install.sh: refusing unsafe shell startup file: ${path_profile}" >&2
    return 1
  }
  if [ -e "$path_profile" ]; then
    # A changed or incomplete managed block needs manual review, not duplication.
    block_state=$(path_export_line | awk '
      NR == FNR { line = $0; next }
      $0 == "# >>> skilak mesh >>>" { starts++; if (getline <= 0 || $0 != line) bad=1; if (getline <= 0 || $0 != "# <<< skilak mesh <<<") bad=1; next }
      $0 == "# <<< skilak mesh <<<" { bad=1 }
      END { if (bad || starts > 1) print "unsafe"; else print starts+0 }
    ' - "$path_profile")
    case "$block_state" in
      1) return 0 ;;
      0) ;;
      *) echo "install.sh: shell PATH block was changed; review ${path_profile}" >&2; return 1 ;;
    esac
  fi
  pending_profile=$(mktemp "${account_home}/.smesh-path.XXXXXX") || return 1
  if [ -e "$path_profile" ]; then
    cat "$path_profile" > "$pending_profile" || { rm -f "$pending_profile"; return 1; }
    profile_mode=$(LC_ALL=C stat -c '%a' "$path_profile" 2>/dev/null || LC_ALL=C stat -f '%Lp' "$path_profile")
    chmod "$profile_mode" "$pending_profile"
  fi
  { printf '\n# >>> skilak mesh >>>\n'; path_export_line; printf '# <<< skilak mesh <<<\n'; } >> "$pending_profile"
  profile_is_safe || { rm -f "$pending_profile"; return 1; }
  mv -f "$pending_profile" "$path_profile"
}

json_escape() {
  awk '
    BEGIN { ORS = "" }
    {
      if (NR > 1) printf "\\n"
      for (position = 1; position <= length($0); position++) {
        character = substr($0, position, 1)
        if (character == "\\") printf "\\\\"
        else if (character == "\"") printf "\\\""
        else if (character == "\t") printf "\\t"
        else if (character == "\r") printf "\\r"
        else printf "%s", character
      }
    }
  '
}

render_receipt() {
  receipt_version=$1
  program_json=$(printf '%s' "$install_prefix" | json_escape)
  launcher_json=$(printf '%s' "$launcher" | json_escape)
  {
    printf '{\n'
    printf '  "schema": 1,\n'
    printf '  "product": "SkilakMesh",\n'
    printf '  "route": "install-sh",\n'
    printf '  "version": "%s",\n' "$receipt_version"
    printf '  "platform": "%s",\n' "$platform_name"
    printf '  "architecture": "%s",\n' "$architecture"
    printf '  "program_root": "%s",\n' "$program_json"
    printf '  "launcher": "%s",\n' "$launcher_json"
    printf '  "service": "%s"\n' "$service_name"
    printf '}\n'
  }
}

write_receipt() {
  pending_receipt="${install_prefix}/.install-receipt.$$"
  render_receipt "$version" > "$pending_receipt"
  chmod 0600 "$pending_receipt"
  mv -f "$pending_receipt" "$receipt"
}

receipt_matches_version() {
  expected_version=$1
  [ -f "$receipt" ] && [ ! -L "$receipt" ] || return 1
  command -v cmp >/dev/null 2>&1 || return 1
  command -v mktemp >/dev/null 2>&1 || return 1
  expected_receipt=$(mktemp "${TMPDIR:-/tmp}/skilakmesh-receipt.XXXXXX") || return 1
  render_receipt "$expected_version" > "$expected_receipt"
  if cmp -s "$receipt" "$expected_receipt"; then
    rm -f "$expected_receipt"
    return 0
  fi
  rm -f "$expected_receipt"
  return 1
}

existing_receipt_matches() {
  [ -f "$receipt" ] && [ ! -L "$receipt" ] || return 1
  existing_version=$(awk '
    NR == 5 {
      value = $0
      if (value !~ /^  "version": "[0-9][0-9.]*",$/) exit 1
      sub(/^  "version": "/, "", value)
      sub(/",$/, "", value)
    }
    END {
      if (NR != 11 || value == "") exit 1
      print value
    }
  ' "$receipt") || return 1
  safe_version_component "$existing_version" || return 1
  receipt_matches_version "$existing_version"
}

prefix_is_recoverable_scaffold() {
  [ -e "$install_prefix" ] || return 0
  first_entry=$(find "$install_prefix" \
    -mindepth 1 -maxdepth 1 -print -quit) || return 1
  [ -n "$first_entry" ] || return 0
  [ -d "${install_prefix}/versions" ] && \
    [ ! -L "${install_prefix}/versions" ] || return 1
  other_entry=$(find "$install_prefix" -mindepth 1 -maxdepth 1 \
    ! -name versions -print -quit) || return 1
  [ -z "$other_entry" ] || return 1
  version_entry=$(find "${install_prefix}/versions" \
    -mindepth 1 -maxdepth 1 -print -quit) || return 1
  [ -z "$version_entry" ] && return 0
  expected_lock="${install_prefix}/versions/.${version}.install.lock"
  [ "$version_entry" = "$expected_lock" ] && \
    [ -d "$expected_lock" ] && [ ! -L "$expected_lock" ] || return 1
  other_version_entry=$(find "${install_prefix}/versions" \
    -mindepth 1 -maxdepth 1 ! -name ".${version}.install.lock" \
    -print -quit) || return 1
  [ -z "$other_version_entry" ]
}

prefix_is_recovery_candidate() {
  [ -d "$install_prefix" ] && [ ! -L "$install_prefix" ] || return 1
  [ -d "${install_prefix}/versions" ] && \
    [ ! -L "${install_prefix}/versions" ] || return 1
  if [ -e "$receipt" ] || [ -L "$receipt" ]; then
    [ -f "$receipt" ] && [ ! -L "$receipt" ] || return 1
  fi
  unexpected_root_entry=$(find "$install_prefix" \
    -mindepth 1 -maxdepth 1 ! -name versions \
    ! -name install-receipt.json -print -quit) || return 1
  [ -z "$unexpected_root_entry" ] || return 1
  [ -d "$version_root" ] && [ ! -L "$version_root" ] || return 1
  unexpected_version=$(find "${install_prefix}/versions" \
    -mindepth 1 -maxdepth 1 ! -name "$version" -print -quit) || return 1
  [ -z "$unexpected_version" ] || return 1
  [ -L "$launcher" ] || return 1
  recovery_launcher_target=$(readlink "$launcher") || return 1
  [ "$recovery_launcher_target" = "${version_root}/smesh" ] || return 1
  launcher_target_is_owned "$recovery_launcher_target"
}

recovery_candidate_is_still_exclusive() {
  unexpected_root_entry=$(find "$install_prefix" \
    -mindepth 1 -maxdepth 1 ! -name versions \
    ! -name install-receipt.json -print -quit) || return 1
  [ -z "$unexpected_root_entry" ] || return 1
  unexpected_version=$(find "${install_prefix}/versions" \
    -mindepth 1 -maxdepth 1 ! -name "$version" \
    ! -name ".${version}.install.lock" \
    ! -name ".${version}.installing.$$" -print -quit) || return 1
  [ -z "$unexpected_version" ] || return 1
  [ -L "$launcher" ] || return 1
  recovery_launcher_target=$(readlink "$launcher") || return 1
  [ "$recovery_launcher_target" = "${version_root}/smesh" ] || return 1
  launcher_target_is_owned "$recovery_launcher_target"
}

tree_entry_details() {
  LC_ALL=C stat -c '%u %a' "$1" 2>/dev/null || \
    LC_ALL=C stat -f '%u %Lp' "$1" 2>/dev/null
}

installed_tree_matches_staged() {
  installed_unsorted="${work_dir}/installed-tree.unsorted"
  staged_unsorted="${work_dir}/staged-tree.unsorted"
  installed_list="${work_dir}/installed-tree.txt"
  staged_list="${work_dir}/staged-tree.txt"
  (cd "$version_root" && LC_ALL=C find . -print) \
    > "$installed_unsorted" || return 1
  (cd "$staged_root" && LC_ALL=C find . -print) \
    > "$staged_unsorted" || return 1
  LC_ALL=C sort "$installed_unsorted" > "$installed_list" || return 1
  LC_ALL=C sort "$staged_unsorted" > "$staged_list" || return 1
  cmp -s "$installed_list" "$staged_list" || return 1
  while IFS= read -r relative; do
    installed_entry="${version_root}/${relative#./}"
    staged_entry="${staged_root}/${relative#./}"
    if [ -L "$staged_entry" ]; then
      [ -L "$installed_entry" ] || return 1
      [ "$(readlink "$installed_entry")" = \
        "$(readlink "$staged_entry")" ] || return 1
    elif [ -d "$staged_entry" ]; then
      [ -d "$installed_entry" ] && [ ! -L "$installed_entry" ] || return 1
      [ "$(tree_entry_details "$installed_entry")" = \
        "$(tree_entry_details "$staged_entry")" ] || return 1
    elif [ -f "$staged_entry" ]; then
      [ -f "$installed_entry" ] && [ ! -L "$installed_entry" ] || return 1
      cmp -s "$installed_entry" "$staged_entry" || return 1
      [ "$(tree_entry_details "$installed_entry")" = \
        "$(tree_entry_details "$staged_entry")" ] || return 1
    else
      return 1
    fi
  done < "$staged_list"
}

launcher_target_is_owned() {
  candidate=$1
  case "$candidate" in
    ''|*//*|*/./*|*/.|*/../*|*/..) return 1 ;;
    "${install_prefix}"/versions/*/smesh) ;;
    *) return 1 ;;
  esac
  candidate_version=${candidate#"${install_prefix}/versions/"}
  candidate_version=${candidate_version%/smesh}
  safe_version_component "$candidate_version" || return 1
  [ "$candidate" = "${install_prefix}/versions/${candidate_version}/smesh" ] || return 1
  path_chain_is_safe "${candidate%/smesh}" || return 1
  [ -f "$candidate" ] && [ ! -L "$candidate" ] && [ -x "$candidate" ]
}

validate_existing_launcher() {
  launcher_target=""
  if [ -e "$launcher" ] || [ -L "$launcher" ]; then
    [ -L "$launcher" ] || {
      echo "install.sh: refusing to replace non-link launcher: ${launcher}" >&2
      return 1
    }
    launcher_target=$(readlink "$launcher") || {
      echo "install.sh: existing launcher cannot be inspected: ${launcher}" >&2
      return 1
    }
    if ! launcher_target_is_owned "$launcher_target"; then
      echo "install.sh: refusing to replace launcher with an unrecognized target: ${launcher}" >&2
      return 1
    fi
  fi
}

activate() {
  [ -x "${version_root}/smesh" ] || {
    echo "install.sh: ${version} is not installed under ${install_prefix}" >&2
    return 1
  }
  install -d -m 0755 "$bin_dir"
  path_chain_is_safe "$bin_dir" || {
    echo "install.sh: launcher directory became unsafe" >&2
    return 1
  }
  validate_existing_launcher || return 1
  pending_launcher="${bin_dir}/.smesh-${version}-$$"
  rm -f "$pending_launcher"
  ln -s "${version_root}/smesh" "$pending_launcher"
  mv -f "$pending_launcher" "$launcher"
  [ "$verbose" -eq 0 ] || echo "Skilak Mesh native ${version} active at ${launcher}"
}

install_service() {
  service_output=$("${version_root}/smesh" --skilak-install-service) || {
    echo "install.sh: command installed, but background service setup failed" >&2
    return 1
  }
  service_outcome=registered
  case "$service_output" in
    'Skilak Mesh native Linux systemd user service upgraded and restarted successfully.'|\
    'Skilak Mesh native macOS launchd user service upgraded; the gateway is running and healthy.')
      service_outcome=restarted ;;
    'Skilak Mesh native Linux systemd user service is already installed; the running gateway was left unchanged.'|\
    'Skilak Mesh native macOS launchd user service is current; the gateway remains running.')
      service_outcome=running ;;
    'Skilak Mesh native Linux systemd user service installed; the gateway was not started.'|\
    'Skilak Mesh native macOS launchd user service installed; the gateway was not started.')
      service_outcome=stopped ;;
  esac
  # The terminal progress runner executes this function in a child shell.
  if [ -n "${work_dir:-}" ]; then
    printf '%s\n' "$service_outcome" > "${work_dir}/service-outcome"
  fi
  [ "$verbose" -eq 0 ] || echo "Skilak Mesh background service is registered for this user."
}

route_notice() {
  if [ "$verbose" -eq 1 ] && [ "$platform_name" = "macOS" ]; then
    echo "This install.sh route installs the command-line tool only; it does not install an app bundle."
  fi
}

next_step_notice() {
  modify_shell_path || return 1
  if [ "$configured_install" -eq 0 ]; then
    printf 'Skilak Mesh %s is installed.\n\nNext, set it up:\n    smesh init\n' "$version"
  else
    if [ "$previous_version" = "$version" ]; then
      printf 'Skilak Mesh %s is already installed and verified.\n' "$version"
    elif [ -n "$previous_version" ]; then
      printf 'Skilak Mesh upgraded to %s (from %s).\n' "$version" "$previous_version"
    else
      printf 'Skilak Mesh %s is installed.\n' "$version"
    fi
    IFS= read -r service_outcome < "${work_dir}/service-outcome"
    case "$service_outcome" in
      restarted) printf 'Your settings and connected clients were kept, and Mesh restarted.\n' ;;
      running) printf 'Your settings and connected clients were kept, and Mesh is still running.\n' ;;
      stopped)
        printf 'Your settings and connected clients were kept.\nMesh is stopped; run smesh start when you are ready.\n' ;;
      *) printf 'Your settings and connected clients were kept.\nRun smesh status to check protection.\n' ;;
    esac
  fi
  if [ "$path_has_bin" -eq 0 ]; then
    printf '\nTo use smesh in this terminal, first run:\n    '
    path_export_line
    if [ "$modify_path" -eq 1 ]; then
      printf '(New terminals already have it.)\n'
    else
      printf '(--no-modify-path: add this line to your shell startup file for new terminals.)\n'
    fi
  fi
}

restore_activate_only_launcher() {
  if [ "$activate_only_had_launcher" -eq 1 ]; then
    restore_launcher="${bin_dir}/.smesh-restore-$$"
    rm -f "$restore_launcher"
    ln -s "$activate_only_launcher_target" "$restore_launcher" || return 1
    mv -f "$restore_launcher" "$launcher" || return 1
    return 0
  fi
  if [ -L "$launcher" ]; then
    rollback_target=$(readlink "$launcher") || return 1
    [ "$rollback_target" = "${version_root}/smesh" ] || return 1
    rm -f "$launcher"
    return
  fi
  [ ! -e "$launcher" ]
}

restore_activate_only_receipt() {
  restore_receipt="${install_prefix}/.install-receipt.restore.$$"
  cp "$activate_only_receipt_backup" "$restore_receipt" || return 1
  chmod 0600 "$restore_receipt" || return 1
  mv -f "$restore_receipt" "$receipt"
}

activate_only_cleanup() {
  rollback_failed=0
  if [ "$activate_only_pending" -eq 1 ]; then
    if [ "$activate_only_launcher_changed" -eq 1 ]; then
      restore_activate_only_launcher || rollback_failed=1
    fi
    restore_activate_only_receipt || rollback_failed=1
    rm -f "${install_prefix}/.install-receipt.$$"
    if [ "$rollback_failed" -eq 1 ]; then
      echo "install.sh: activation rollback was incomplete; inspect the launcher and receipt" >&2
    fi
  fi
  [ -z "$activate_only_receipt_backup" ] || \
    rm -f "$activate_only_receipt_backup"
}

if [ "$activate_only" -eq 1 ]; then
  for tool in chmod cmp cp install ln mktemp mv readlink rm; do
    command -v "$tool" >/dev/null 2>&1 || {
      echo "install.sh: ${tool} is required" >&2
      exit 1
    }
  done
  existing_receipt_matches || {
    echo "install.sh: --activate-only requires an exact verified install receipt for this program root" >&2
    exit 1
  }
  "${version_root}/smesh" --skilak-native-self-check >/dev/null || {
    echo "install.sh: installed native artifact self-check failed" >&2
    exit 1
  }
  "${version_root}/smesh" --skilak-native-containment-self-check >/dev/null || {
    echo "install.sh: installed native containment self-check failed" >&2
    exit 1
  }
  validate_existing_launcher || exit 1
  activate_only_had_launcher=0
  activate_only_launcher_target=""
  if [ -L "$launcher" ]; then
    activate_only_had_launcher=1
    activate_only_launcher_target=$launcher_target
  fi
  activate_only_receipt_backup=$(mktemp \
    "${TMPDIR:-/tmp}/skilakmesh-receipt-backup.XXXXXX")
  cp "$receipt" "$activate_only_receipt_backup"
  activate_only_pending=1
  activate_only_launcher_changed=0
  trap activate_only_cleanup EXIT
  trap 'exit 1' HUP INT TERM
  write_receipt
  if ! activate; then
    exit 1
  fi
  activate_only_launcher_changed=1
  if ! install_service; then
    exit 1
  fi
  activate_only_pending=0
  trap - EXIT HUP INT TERM
  rm -f "$activate_only_receipt_backup"
  activate_only_receipt_backup=""
  route_notice
  exit 0
fi

if [ -n "$source_dir" ]; then
  case "$source_commit" in
    ''|*[!0-9a-f]*)
      echo "install.sh: a reviewed lowercase source commit is required for offline provenance verification" >&2
      exit 1
      ;;
  esac
  [ "${#source_commit}" -eq 40 ] || {
    echo "install.sh: source commit must be exactly 40 lowercase hexadecimal characters" >&2
    exit 1
  }
  [ -n "$trusted_root" ] || {
    echo "install.sh: --trusted-root is required with --source-dir for offline provenance verification" >&2
    exit 1
  }
  [ -f "$trusted_root" ] || {
    echo "install.sh: trusted root is unavailable" >&2
    exit 1
  }
  [ "$source_ref" = "refs/tags/v${version}" ] || {
    echo "install.sh: --source-ref must be the exact refs/tags/v${version} release identity" >&2
    exit 1
  }
elif [ -n "$source_commit" ] || [ -n "$trusted_root" ] || \
    [ "$source_ref_explicit" -eq 1 ]; then
  echo "install.sh: --source-commit, --source-ref, and --trusted-root are offline options that require --source-dir" >&2
  exit 1
fi

for tool in awk chmod cmp cp find install ln mkdir mktemp mv readlink rm rmdir sort; do
  command -v "$tool" >/dev/null 2>&1 || {
    echo "install.sh: ${tool} is required" >&2
    exit 1
  }
done

recovery_candidate=0
repeat_candidate=0
if existing_receipt_matches; then
  previous_version=$existing_version
elif prefix_is_recoverable_scaffold; then
  :
elif prefix_is_recovery_candidate; then
  recovery_candidate=1
else
  echo "install.sh: refusing to adopt a nonempty installation prefix without an exact verified install receipt: ${install_prefix}" >&2
  exit 1
fi

if [ "$archive_type" = "tar" ]; then
  for tool in getconf tar; do
    command -v "$tool" >/dev/null 2>&1 || {
      echo "install.sh: ${tool} is required" >&2
      exit 1
    }
  done
  libc_report=$(getconf GNU_LIBC_VERSION 2>/dev/null || true)
  case "$libc_report" in
    "glibc "*) libc_version=${libc_report#glibc } ;;
    *)
      echo "install.sh: this artifact requires glibc 2.39 or newer" >&2
      exit 1
      ;;
  esac
  libc_major=${libc_version%%.*}
  libc_minor=${libc_version#*.}
  libc_minor=${libc_minor%%.*}
  case "${libc_major}:${libc_minor}" in
    *[!0-9:]*|:|*:)
      echo "install.sh: glibc version could not be verified" >&2
      exit 1
      ;;
  esac
  if [ "$libc_major" -lt 2 ] || {
       [ "$libc_major" -eq 2 ] && [ "$libc_minor" -lt 39 ];
     }; then
    echo "install.sh: this artifact requires glibc 2.39 or newer (Ubuntu 24.04 baseline)" >&2
    exit 1
  fi
else
  [ -x /usr/bin/ditto ] || {
    echo "install.sh: /usr/bin/ditto is required" >&2
    exit 1
  }
  [ -x /bin/realpath ] || {
    echo "install.sh: /bin/realpath is required" >&2
    exit 1
  }
  [ -x /usr/bin/readlink ] || {
    echo "install.sh: /usr/bin/readlink is required" >&2
    exit 1
  }
  [ -x /usr/bin/env ] || {
    echo "install.sh: /usr/bin/env is required" >&2
    exit 1
  }
fi

umask 077

# Slow steps animate a spinner on a terminal so the install never looks stuck;
# pipes and logs get no animation. Each finished step leaves one checked line.
spin_pid=""
progress_tty=0
if [ -t 2 ] && [ "${TERM:-dumb}" != dumb ]; then
  progress_tty=1
fi
case "${LC_ALL:-${LC_CTYPE:-${LANG:-}}}" in
  *[Uu][Tt][Ff]-8*|*[Uu][Tt][Ff]8*)
    progress_frames='⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏'; progress_ok='✓'; progress_more='…' ;;
  *)
    progress_frames='| / - \'; progress_ok='ok'; progress_more='...' ;;
esac

step_note() {
  [ "$progress_tty" -eq 0 ] || printf '%s %s\n' "$progress_ok" "$1" >&2
}

# step MESSAGE DONE_TEXT COMMAND [ARGS...]: run COMMAND, animating MESSAGE.
step() {
  step_message=$1
  step_done=$2
  shift 2
  if [ "$progress_tty" -eq 0 ]; then
    "$@"
    return
  fi
  "$@" &
  spin_pid=$!
  while kill -0 "$spin_pid" 2>/dev/null; do
    for frame in $progress_frames; do
      kill -0 "$spin_pid" 2>/dev/null || break
      printf '\r\033[K%s %s%s' "$frame" "$step_message" "$progress_more" >&2
      sleep 0.1
    done
  done
  step_status=0
  wait "$spin_pid" || step_status=$?
  spin_pid=""
  printf '\r\033[K' >&2
  [ "$step_status" -ne 0 ] || step_note "$step_done"
  return "$step_status"
}
work_dir=$(mktemp -d "${TMPDIR:-/tmp}/skilakmesh-install.XXXXXX")
staged_root=""
staged_container=""
install_lock=""
lock_acquired=0
version_published=0
ownership_committed=0
cleanup() {
  if [ -n "$spin_pid" ]; then
    kill "$spin_pid" 2>/dev/null || true
    printf '\r\033[K' >&2
  fi
  rm -rf "$work_dir"
  if [ -n "$staged_root" ]; then
    rm -rf "$staged_root"
  fi
  if [ -n "$staged_container" ]; then
    rm -rf "$staged_container"
  fi
  if [ "$lock_acquired" -eq 1 ]; then
    rmdir "$install_lock" 2>/dev/null || true
  fi
  if [ "$version_published" -eq 1 ] && [ "$ownership_committed" -ne 1 ]; then
    rm -rf "$version_root"
  fi
}
trap cleanup EXIT HUP INT TERM

if [ -n "$source_dir" ]; then
  [ -f "${source_dir}/${archive_name}" ] || {
    echo "install.sh: ${source_dir}/${archive_name} is missing" >&2
    exit 1
  }
  [ -f "${source_dir}/${checksums_name}" ] || {
    echo "install.sh: ${source_dir}/${checksums_name} is missing" >&2
    exit 1
  }
  [ -f "${source_dir}/${record_name}" ] || {
    echo "install.sh: ${source_dir}/${record_name} is missing" >&2
    exit 1
  }
  [ -f "${source_dir}/${provenance_name}" ] || {
    echo "install.sh: ${source_dir}/${provenance_name} is missing; provenance is required" >&2
    exit 1
  }
  cp "${source_dir}/${archive_name}" "$work_dir/"
  cp "${source_dir}/${record_name}" "$work_dir/"
  cp "${source_dir}/${checksums_name}" "$work_dir/"
  cp "${source_dir}/${provenance_name}" "$work_dir/"
else
  case "$expected_archive_sha256" in
    *[!0-9a-f]*|'')
      echo "install.sh: this installer has no valid embedded SHA-256 for ${platform_name} ${architecture}" >&2
      exit 1
      ;;
  esac
  [ "${#expected_archive_sha256}" -eq 64 ] || {
    echo "install.sh: this installer has no valid embedded SHA-256 for ${platform_name} ${architecture}" >&2
    exit 1
  }
  command -v curl >/dev/null 2>&1 || {
    echo "install.sh: curl is required for an online install; use --source-dir for an offline install" >&2
    exit 1
  }
  step "Downloading Skilak Mesh ${version}" "Downloaded Skilak Mesh ${version}" \
    curl --fail --location --silent --show-error \
    --proto '=https' --proto-redir '=https' --tlsv1.2 \
    "${asset_origin}/${archive_name}${download_query}" \
    --output "$work_dir/$archive_name" || {
      echo "install.sh: download failed for ${asset_origin}/${archive_name}" >&2
      exit 1
    }
fi

trusted_root_copy=""
if [ -n "$source_dir" ]; then
  command -v gh >/dev/null 2>&1 || {
    echo "install.sh: GitHub CLI is required for offline provenance verification" >&2
    exit 1
  }
  trusted_root_copy="$work_dir/trusted-root.jsonl"
  cp "$trusted_root" "$trusted_root_copy"
  gh attestation verify "$work_dir/$checksums_name" \
    --repo "$source_repository" \
    --bundle "$work_dir/$provenance_name" \
    --custom-trusted-root "$trusted_root_copy" \
    --cert-identity "https://github.com/$source_repository/.github/workflows/release.yml@$source_ref" \
    --cert-oidc-issuer https://token.actions.githubusercontent.com \
    --source-ref "$source_ref" \
    --source-digest "$source_commit" \
    --predicate-type https://slsa.dev/provenance/v1 >/dev/null 2>&1 || {
      echo "install.sh: provenance verification failed for ${checksums_name}" >&2
      exit 1
    }
  manifest_names_file="$work_dir/manifest-names.txt"
  awk '
    NF != 2 || $1 !~ /^[0-9a-f]{64}$/ || $2 !~ /^[A-Za-z0-9._-]+$/ || seen[$2]++ {
      bad = 1
    }
    { print $2 }
    END { exit bad ? 1 : 0 }
  ' "$work_dir/$checksums_name" > "$manifest_names_file" || {
    echo "install.sh: ${checksums_name} has an invalid entry" >&2
    exit 1
  }
  manifest_names_sorted="$work_dir/manifest-names-sorted.txt"
  LC_ALL=C sort "$manifest_names_file" > "$manifest_names_sorted"
  manifest_names=$(awk '{ print }' "$manifest_names_sorted")
  selected_names=$(printf '%s\n%s\n' "$archive_name" "$record_name" | LC_ALL=C sort)
  names_are_allowed=0
  if [ "$manifest_names" = "$selected_names" ]; then
    names_are_allowed=1
  elif [ "$platform_name" = "macOS" ]; then
    all_macos_names=$(printf '%s\n' \
      "skilakmesh-${version}-macos-arm64-cli.zip" \
      "skilakmesh-${version}-macos-arm64-cli.build.json" \
      "skilakmesh-${version}-macos-x86_64-cli.zip" \
      "skilakmesh-${version}-macos-x86_64-cli.build.json" | LC_ALL=C sort)
    [ "$manifest_names" = "$all_macos_names" ] && names_are_allowed=1
  fi
  [ "$names_are_allowed" -eq 1 ] || {
    echo "install.sh: ${checksums_name} has the wrong file set" >&2
    exit 1
  }

  expected_archive_offline_sha256=$(awk -v name="$archive_name" \
    '$2 == name { print $1 }' "$work_dir/$checksums_name")
  expected_record_offline_sha256=$(awk -v name="$record_name" \
    '$2 == name { print $1 }' "$work_dir/$checksums_name")
  if command -v sha256sum >/dev/null 2>&1; then
    actual_archive_offline_sha256=$(sha256sum \
      "$work_dir/$archive_name" | awk '{print $1}')
    actual_record_offline_sha256=$(sha256sum \
      "$work_dir/$record_name" | awk '{print $1}')
  elif command -v shasum >/dev/null 2>&1; then
    actual_archive_offline_sha256=$(shasum -a 256 \
      "$work_dir/$archive_name" | awk '{print $1}')
    actual_record_offline_sha256=$(shasum -a 256 \
      "$work_dir/$record_name" | awk '{print $1}')
  else
    echo "install.sh: sha256sum or shasum is required" >&2
    exit 1
  fi
  [ "$actual_archive_offline_sha256" = "$expected_archive_offline_sha256" ] && \
    [ "$actual_record_offline_sha256" = "$expected_record_offline_sha256" ] || {
      echo "install.sh: native release checksum verification failed" >&2
      exit 1
    }
else
  if command -v sha256sum >/dev/null 2>&1; then
    actual_archive_sha256=$(sha256sum "$work_dir/$archive_name" | awk '{print $1}')
  elif command -v shasum >/dev/null 2>&1; then
    actual_archive_sha256=$(shasum -a 256 "$work_dir/$archive_name" | awk '{print $1}')
  else
    echo "install.sh: sha256sum or shasum is required" >&2
    exit 1
  fi
  [ "$actual_archive_sha256" = "$expected_archive_sha256" ] || {
    echo "install.sh: downloaded archive SHA-256 verification failed" >&2
    exit 1
  }
fi
step_note "Verified the download"

member_list="$work_dir/archive-members.txt"
mode_list="$work_dir/archive-modes.txt"
if [ "$archive_type" = "tar" ]; then
  LC_ALL=C tar -tzf "$work_dir/$archive_name" > "$member_list"
  [ -s "$member_list" ] || {
    echo "install.sh: native archive is empty" >&2
    exit 1
  }
  awk '
    {
      name = $0
      sub(/\/$/, "", name)
      count = split(name, parts, "/")
      if (count < 1 || parts[1] != "smesh") bad = 1
      for (part = 1; part <= count; part++)
        if (parts[part] == "" || parts[part] == "." || parts[part] == "..") bad = 1
    }
    END { exit bad ? 1 : 0 }
  ' "$member_list" || {
    echo "install.sh: native archive contains an unsafe path" >&2
    exit 1
  }
  LC_ALL=C tar -tvzf "$work_dir/$archive_name" > "$mode_list"
  awk 'substr($0, 1, 1) != "-" && substr($0, 1, 1) != "d" { bad = 1 } END { exit bad ? 1 : 0 }' "$mode_list" || {
    echo "install.sh: native archive contains a link or special file" >&2
    exit 1
  }
fi

install -d -m 0755 "${install_prefix}/versions"
path_chain_is_safe "$install_prefix" || {
  echo "install.sh: installation prefix became unsafe" >&2
  exit 1
}
install_lock="${install_prefix}/versions/.${version}.install.lock"
if ! mkdir "$install_lock" 2>/dev/null; then
  echo "install.sh: another ${version} installation is active or left a reviewed lock at ${install_lock}" >&2
  exit 1
fi
lock_acquired=1

if [ "$recovery_candidate" -eq 1 ]; then
  [ -d "$version_root" ] && [ ! -L "$version_root" ] || {
    echo "install.sh: recovery candidate changed before verification" >&2
    exit 1
  }
else
  if [ -e "$version_root" ] || [ -L "$version_root" ]; then
    [ -d "$version_root" ] && [ ! -L "$version_root" ] &&
      receipt_matches_version "$version" || {
      echo "install.sh: ${version_root} already exists without current-version ownership" >&2
      exit 1
    }
    repeat_candidate=1
  fi
fi
staged_root="${install_prefix}/versions/.${version}.installing.$$"
[ ! -e "$staged_root" ] || {
  echo "install.sh: staging directory already exists" >&2
  exit 1
}
if [ "$archive_type" = "tar" ]; then
  install -d -m 0755 "$staged_root"
  step "Unpacking" "Unpacked" \
    tar -xzf "$work_dir/$archive_name" -C "$staged_root" \
    --strip-components 1 --no-same-owner --no-same-permissions
else
  staged_container="${install_prefix}/versions/.${version}.archive.$$"
  [ ! -e "$staged_container" ] || {
    echo "install.sh: archive staging directory already exists" >&2
    exit 1
  }
  install -d -m 0755 "$staged_container"
  step "Unpacking" "Unpacked" /usr/bin/env -i PATH=/usr/bin:/bin DITTOABORT=1 \
    /usr/bin/ditto -x -k "$work_dir/$archive_name" "$staged_container" || {
    echo "install.sh: native archive could not be extracted" >&2
    exit 1
  }
  top_count=$(find "$staged_container" -mindepth 1 -maxdepth 1 -print | \
    awk 'END { print NR }')
  [ "$top_count" -eq 1 ] && [ -d "$staged_container/smesh" ] && \
    [ ! -L "$staged_container/smesh" ] || {
    echo "install.sh: native archive has no smesh onedir tree" >&2
    exit 1
  }
  if find "$staged_container/smesh" \
      ! -type f ! -type d ! -type l -print -quit | \
      awk 'NF { found = 1 } END { exit found ? 0 : 1 }'; then
    echo "install.sh: native archive contains a special file" >&2
    exit 1
  fi
  tree_root=$(/bin/realpath "$staged_container/smesh") || {
    echo "install.sh: native archive root cannot be resolved" >&2
    exit 1
  }
  find "$tree_root" -print > "$member_list"
  if ! find "$tree_root" -type l -exec sh -c '
    root=$1
    shift
    for link do
      target=$(/usr/bin/readlink "$link") || exit 1
      case "$target" in ""|/*) exit 1 ;; esac
      resolved=$(/bin/realpath "$link") || exit 1
      case "$resolved" in "$root"|"$root"/*) ;; *) exit 1 ;; esac
    done
  ' sh "$tree_root" {} +; then
    echo "install.sh: native archive contains an unsafe link" >&2
    exit 1
  fi
  mv "$staged_container/smesh" "$staged_root"
  rmdir "$staged_container"
  staged_container=""
fi

[ -x "$staged_root/smesh" ] || {
  echo "install.sh: native archive has no executable smesh dispatcher" >&2
  exit 1
}
[ -d "$staged_root/_internal" ] || {
  echo "install.sh: native archive has no PyInstaller runtime tree" >&2
  exit 1
}
[ -f "$staged_root/native-build.json" ] || {
  echo "install.sh: native archive has no build record" >&2
  exit 1
}
if [ "$archive_type" = "tar" ] && \
    find "$staged_root" -type l -print -quit | \
      awk 'NF { found = 1 } END { exit found ? 0 : 1 }'; then
  echo "install.sh: extracted native tree contains a link" >&2
  exit 1
fi

run_self_checks() {
  "$staged_root/smesh" --skilak-native-self-check >/dev/null || {
    echo "install.sh: native artifact self-check failed" >&2
    return 1
  }
  "$staged_root/smesh" --skilak-native-containment-self-check >/dev/null || {
    echo "install.sh: native containment self-check failed" >&2
    return 1
  }
}
step "Checking the build" "Checked the build" run_self_checks || exit 1

validate_existing_launcher || exit 1

if [ "$repeat_candidate" -eq 1 ]; then
  [ "$launcher_target" = "${version_root}/smesh" ] &&
    installed_tree_matches_staged || {
    echo "install.sh: existing version does not exactly match the verified release" >&2
    exit 1
  }
  step "Setting up the background service" "Background service ready" install_service
  [ "$verbose" -eq 0 ] || echo "Skilak Mesh native ${version} is already installed and verified at ${launcher}"
  route_notice
  next_step_notice
  exit 0
fi

if [ "$recovery_candidate" -eq 1 ]; then
  recovery_candidate_is_still_exclusive && installed_tree_matches_staged || {
    echo "install.sh: receipt-free installation does not exactly match the verified release; no ownership was claimed" >&2
    exit 1
  }
  write_receipt
  activate
  step "Setting up the background service" "Background service ready" install_service
  route_notice
  [ "$verbose" -eq 0 ] || echo "Skilak Mesh native ${version} ownership receipt was safely recovered."
  next_step_notice
  exit 0
fi

mv "$staged_root" "$version_root"
staged_root=""
version_published=1
write_receipt
ownership_committed=1
activate
step "Setting up the background service" "Background service ready" install_service
route_notice
next_step_notice
