#!/bin/sh
set -eu
# Glaresigne bootstrap installer.
#
#   curl -fsSL https://glaresigne.corasigne.net/install.sh | sudo sh
#
# Downloads the glaresigne-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 `glaresigne-cli install`, e.g.:
#   curl -fsSL https://glaresigne.corasigne.net/install.sh | sudo sh -s -- --domain example.com
#
# Override the release host with GLARESIGNE_BASE_URL:
#   curl -fsSL .../install.sh | sudo GLARESIGNE_BASE_URL=https://staging.example.net sh

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

if [ "$(id -u)" -ne 0 ]; then
  echo "glaresigne: 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 "glaresigne: '$tool' is required" >&2; exit 1; }
done

TMP="$(mktemp -d)"; trap 'rm -rf "$TMP"' EXIT
CLI="glaresigne-cli-$OS-$ARCH"
echo "→ downloading $CLI from $BASE …"
curl -fsSL "$BASE/$CLI"      -o "$TMP/glaresigne-cli"
curl -fsSL "$BASE/$CLI.sig"  -o "$TMP/glaresigne-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/glaresigne-cli" -sigfile "$TMP/glaresigne-cli.sig" >/dev/null 2>&1; then
  echo "glaresigne: ✗ signature verification FAILED — refusing to install" >&2
  exit 1
fi
echo "  ✓ signature OK"

install -m 0755 "$TMP/glaresigne-cli" /usr/local/bin/glaresigne-cli
echo "→ running installer …"
exec /usr/local/bin/glaresigne-cli install "$@"
