#!/bin/sh
set -eu
# Zaphyio bootstrap installer.
#
#   curl -fsSL https://zaphyio.com/install.sh | sudo sh
#
# Downloads the zaphyio-cli binary, its detached Ed25519 signature, and the
# release public key from the release host, verifies the signature with openssl
# (fail-closed), installs the cli to /usr/local/bin, and runs the installer.
#
# Anything after `sh -s --` is forwarded to `zaphyio-cli install`, e.g.:
#   curl -fsSL https://zaphyio.com/install.sh | sudo sh -s -- --domain example.com
#
# Override the release host with ZAPHYIO_BASE_URL:
#   curl -fsSL .../install.sh | sudo ZAPHYIO_BASE_URL=https://staging.example.net sh

BASE="${ZAPHYIO_BASE_URL:-https://zaphyio.com}"
OS=linux
ARCH="$(uname -m)"
case "$ARCH" in
  x86_64|amd64) ARCH=amd64 ;;
  aarch64|arm64) ARCH=arm64 ;;
  *) echo "zaphyio: unsupported architecture: $ARCH" >&2; exit 1 ;;
esac

if [ "$(id -u)" -ne 0 ]; then
  echo "zaphyio: please run as root (e.g. pipe to 'sudo sh')" >&2; exit 1
fi
for tool in curl openssl install; do
  command -v "$tool" >/dev/null 2>&1 || { echo "zaphyio: '$tool' is required" >&2; exit 1; }
done

TMP="$(mktemp -d)"; trap 'rm -rf "$TMP"' EXIT
CLI="zaphyio-cli-$OS-$ARCH"
echo "→ downloading $CLI from $BASE …"
curl -fsSL "$BASE/$CLI"      -o "$TMP/zaphyio-cli"
curl -fsSL "$BASE/$CLI.sig"  -o "$TMP/zaphyio-cli.sig"
curl -fsSL "$BASE/release.pub" -o "$TMP/release.pub"

echo "→ verifying Ed25519 signature …"
if ! openssl pkeyutl -verify -pubin -inkey "$TMP/release.pub" -rawin \
      -in "$TMP/zaphyio-cli" -sigfile "$TMP/zaphyio-cli.sig" >/dev/null 2>&1; then
  echo "zaphyio: ✗ signature verification FAILED - refusing to install" >&2
  exit 1
fi
echo "  ✓ signature OK"

install -m 0755 "$TMP/zaphyio-cli" /usr/local/bin/zaphyio-cli
echo "→ running installer …"
# Pass the same release host so the installer fetches the signed bundle (the rest
# of the binaries) from where the cli came. The bundle version comes from the
# cli's own version.Version(); --release-base is overridden by an explicit
# --bundle-url in "$@" if the operator supplies one.
exec /usr/local/bin/zaphyio-cli install --release-base "$BASE" "$@"
