#!/usr/bin/env bash
# Nemesis quickstart installer.
#
# Downloads the correct Nemesis evaluation archive for this host's
# architecture, verifies its checksum, extracts it, and hands off to the
# bundled install-nemesis.sh (which requires sudo and does the real work:
# service accounts, systemd units, TLS, and guided commissioning).
#
# Usage:
#   curl -fsSL https://advanceddatamachines.com/downloads/install.sh | bash
#
# Extra arguments after the script are passed through to install-nemesis.sh,
# e.g. for a customer-PKI certificate:
#   curl -fsSL .../install.sh | bash -s -- --tls-certificate ./chain.pem --tls-private-key ./key.pem

set -euo pipefail

VERSION="2.30.0-alpha.2"
BASE_URL="${NEMESIS_DOWNLOAD_ROOT:-https://advanceddatamachines.com}/downloads"

if [ "$(uname -s)" != "Linux" ]; then
    echo "Nemesis requires a Debian-family Linux host; detected $(uname -s)." >&2
    exit 1
fi

if [ -r /etc/os-release ] && ! grep -qiE '^(ID|ID_LIKE)=.*debian' /etc/os-release; then
    echo "Warning: this does not look like a Debian-family host. Continuing anyway." >&2
fi

arch="$(uname -m)"
case "$arch" in
    x86_64)
        # NOTE: only the musl (GLIBC-compatibility) x86_64 archive is
        # published today; there is no separate standard glibc build yet.
        archive="nemesis-${VERSION}-x86_64-musl.tar.gz"
        ;;
    aarch64 | arm64)
        archive="nemesis-${VERSION}-aarch64.tar.gz"
        ;;
    *)
        echo "Unsupported architecture: ${arch}. Nemesis currently ships for x86_64 and aarch64." >&2
        exit 1
        ;;
esac

workdir="$(mktemp -d)"
trap 'rm -rf "$workdir"' EXIT
cd "$workdir"

echo "Downloading ${archive}..."
curl -fsSL -O "${BASE_URL}/${archive}"
curl -fsSL -O "${BASE_URL}/${archive}.sha256"

echo "Verifying archive checksum..."
sha256sum --check "${archive}.sha256"

echo "Extracting..."
tar -xzf "${archive}"
cd "${archive%.tar.gz}"

echo "Verifying bundle contents..."
sha256sum --check SHA256SUMS

echo "Running install-nemesis.sh (requires sudo)..."
sudo ./install-nemesis.sh "$@"
