#!/usr/bin/env bash
# Generated immutable HTTP installer; no Git, Docker pull or credentials needed to fetch.
set -euo pipefail
revision='c6215ee24ebaf73089eec12561b22b2a6e8251a4'
archive_sha='217531f5e4a2a5e77a692c9be1b5a943c0a40871cc092f640465779dbc072c50'
release_url='https://gitea.claw.ethanmartin.cn/api/packages/gitea/generic/incus-mcp-adapter-deploy/c6215ee24ebaf73089eec12561b22b2a6e8251a4'
prefix="${PWD}/incus-mcp-adapter"
bootstrap=0
while (( $# )); do
  case "$1" in
    --prefix) [[ $# -ge 2 ]] || { echo 'Missing --prefix value' >&2; exit 2; }; prefix="$2"; shift 2 ;;
    --bootstrap) bootstrap=1; shift ;;
    --download-only) bootstrap=0; shift ;;
    *) echo 'Usage: install.sh [--prefix DIRECTORY] [--download-only|--bootstrap]' >&2; exit 2 ;;
  esac
done
[[ -n "$prefix" ]] || { echo 'Empty install prefix refused' >&2; exit 2; }
if (( bootstrap )) && [[ $EUID != 0 ]]; then
  echo 'Run --bootstrap as root; it installs Incus and the bounded network unit' >&2; exit 1
fi
work="$(mktemp -d)"
trap 'rm -rf "$work"' EXIT
curl -q --fail --silent --show-error --location --proto '=https' --proto-redir '=https' \
  --connect-timeout 10 --max-time 120 "$release_url/incus-deploy.tar.gz" -o "$work/incus-deploy.tar.gz"
printf '%s  %s\n' "$archive_sha" "$work/incus-deploy.tar.gz" | sha256sum -c -
name="incus-deploy-${revision:0:12}"
while IFS= read -r entry; do
  [[ "$entry" == "$name/"* && "$entry" != *..* ]] || { echo 'Unsafe archive member' >&2; exit 1; }
done < <(tar -tzf "$work/incus-deploy.tar.gz")
tar -xzf "$work/incus-deploy.tar.gz" -C "$work"
"$work/$name/scripts/verify-bundle.sh" >/dev/null
source "$work/$name/scripts/release-lib.sh"
load_release "$work/$name" "$revision"
mkdir -p "$prefix/releases"
prefix="$(cd "$prefix" && pwd)"
target="$prefix/releases/$revision"
if [[ -e "$target" ]]; then
  "$target/scripts/verify-bundle.sh" >/dev/null
  cmp "$work/$name/release.env" "$target/release.env" || { echo 'Existing release identity differs' >&2; exit 1; }
else
  # Stage on the target filesystem so the final rename is atomic.
  stage="$(mktemp -d "$prefix/releases/.staging.XXXXXX")"
  cp -a "$work/$name/." "$stage/"
  mv "$stage" "$target"
fi
if (( bootstrap )); then
  "$target/scripts/bootstrap-host.sh"
  "$target/scripts/network-egress.sh" install incusbr0
fi
[[ ! -e "$prefix/current" || -L "$prefix/current" ]] || { echo 'current exists and is not a release symlink' >&2; exit 1; }
ln -sfn "$target" "$prefix/current"
printf 'Installed verified deployment bundle: %s\n' "$target"
echo 'Runtime Tunnel credentials and Compose deployment are configured separately; see docs/deployment.md.'
