#!/bin/sh
# Secria VPN — one-line installer.
#
#   curl -fsSL https://secria.me/install.sh | sudo sh
#
# Downloads the static tarball and verifies BOTH its SHA-256 (against
# SHA256SUMS) and the SLH-DSA post-quantum release signature on SHA256SUMS
# itself (via the bundled sphincs-verify tool, which is hash-pinned below).
# Fails closed: nothing is installed unless every enabled verification passes.
#
# Overridable via env:
#   SECRIA_BASE_URL   host root                      (default https://secria.me)
#   SECRIA_VERSION    version for the tarball path   (default latest)
#   SECRIA_BIN_DIR    binary install dir override    (default /usr/local/bin)
set -eu

BASE_URL="${SECRIA_BASE_URL:-https://secria.me}"
VERSION="${SECRIA_VERSION:-latest}"

# --- Pinned trust anchors ----------------------------------------------------
# Filled in by release engineering when the corresponding key exists; a value
# still wrapped in __…__ means "not yet pinned" and disables that verification
# path with a loud warning (pre-release bootstrap only — before public launch
# every pin below MUST be set, making verification fail-closed).
#
# SHA-256 of the PEM-encoded SLH-DSA release public key served at /keys/release-slhdsa.pub.
RELEASE_PUBKEY_SHA256="a4660918748c980dc00b935ed2ede5ef18722a384f15a932e7246e9427b2eddb"
# SHA-256 of the standalone sphincs-verify tool binaries served under
# /download/tools/. Pinning the verifier here breaks the circular dependency of
# using a downloaded verifier to verify the download that contains it. The
# tool is republished under a versioned name every release, so the version the
# hashes pin is part of the anchor — all three values move together in one
# commit (a fixed URL would change hash under the pins on the next release).
SPHINCS_TOOL_SHA256_AMD64="ca2e4377781d25ad787a59e234d6a19ba1121517317b9e2bd8756b7e7db6dfb3"
SPHINCS_TOOL_SHA256_ARM64="e6706a630c660869385ba6ea1a13cf8952bbd8e5f38592f1d6bf9a62c1208a7c"
SPHINCS_TOOL_VERSION="1.0.4"

say() { printf '%s\n' "$*"; }
warn() { printf 'secria-vpn install: WARNING: %s\n' "$*" >&2; }
die() { printf 'secria-vpn install: %s\n' "$*" >&2; exit 1; }

# A pin is usable only when release engineering replaced the __…__ placeholder.
pin_set() {
	case "$1" in
	'' | __SECRIA_*__) return 1 ;;
	*) return 0 ;;
	esac
}

[ "$(uname -s)" = "Linux" ] || die "this installer supports Linux only"
[ "$(id -u)" -eq 0 ] || die "run as root, e.g.: curl -fsSL $BASE_URL/install.sh | sudo sh"

case "$(uname -m)" in
	x86_64 | amd64)  ARCH=amd64;  SPHINCS_TOOL_SHA256="$SPHINCS_TOOL_SHA256_AMD64" ;;
	aarch64 | arm64) ARCH=arm64;  SPHINCS_TOOL_SHA256="$SPHINCS_TOOL_SHA256_ARM64" ;;
	*) die "unsupported architecture: $(uname -m) (supported: amd64, arm64)" ;;
esac

if command -v curl >/dev/null 2>&1; then
	fetch() { curl -fsSL "$1" -o "$2"; }
elif command -v wget >/dev/null 2>&1; then
	fetch() { wget -qO "$2" "$1"; }
else
	die "need curl or wget"
fi
command -v sha256sum >/dev/null 2>&1 || die "need sha256sum (coreutils)"

TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT INT TERM

# --- Static tarball (SHA-256 + SLH-DSA verified) -----------------------------

TARBALL="secria-vpn-${VERSION}-linux-${ARCH}.tar.gz"

say "Downloading ${TARBALL}..."
fetch "$BASE_URL/download/linux/$TARBALL" "$TMP/$TARBALL" || die "download failed: $BASE_URL/download/linux/$TARBALL"

# Linux-scoped, independently-signed manifest so a Windows/macOS release can't invalidate the Linux one-liner's SLH-DSA signature; fall back to the shared manifest on older hosts.
MANIFEST=SHA256SUMS.linux
if fetch "$BASE_URL/$MANIFEST" "$TMP/$MANIFEST"; then
	:
else
	MANIFEST=SHA256SUMS
	fetch "$BASE_URL/$MANIFEST" "$TMP/$MANIFEST" || die "could not fetch checksums"
fi

# SLH-DSA (post-quantum) release signature over SHA256SUMS. Verifying this one
# file extends trust to every artifact listed in it. Enabled once the pins at
# the top of this script are set; a tampered SHA256SUMS, public key, or
# verifier binary is always fatal — never a fallback.
#
# The four SLH-DSA pins are published as one block (the release summary emits
# key hash, both tool hashes, and the tool version together), so a mixed state
# is never a legitimate build — only an operator slip. Warning-and-skipping on
# it would silently downgrade an installer that was meant to verify: hard stop.
PINS_SET=0
for PIN in "$RELEASE_PUBKEY_SHA256" "$SPHINCS_TOOL_SHA256_AMD64" "$SPHINCS_TOOL_SHA256_ARM64" "$SPHINCS_TOOL_VERSION"; do
	if pin_set "$PIN"; then PINS_SET=$((PINS_SET + 1)); fi
done
if [ "$PINS_SET" -ne 0 ] && [ "$PINS_SET" -ne 4 ]; then
	die "inconsistent SLH-DSA trust anchors ($PINS_SET of 4 pinned) — set RELEASE_PUBKEY_SHA256, SPHINCS_TOOL_SHA256_AMD64, SPHINCS_TOOL_SHA256_ARM64 and SPHINCS_TOOL_VERSION together (all four are emitted by the release publish summary)"
fi

if pin_set "$RELEASE_PUBKEY_SHA256" && pin_set "$SPHINCS_TOOL_SHA256" && pin_set "$SPHINCS_TOOL_VERSION"; then
	say "Verifying SLH-DSA release signature..."
	SPHINCS_TOOL="sphincs-verify-${SPHINCS_TOOL_VERSION}-linux-${ARCH}"
	fetch "$BASE_URL/${MANIFEST}.sig"                 "$TMP/${MANIFEST}.sig" || die "could not fetch ${MANIFEST}.sig"
	fetch "$BASE_URL/keys/release-slhdsa.pub"         "$TMP/release.pub"    || die "could not fetch release public key"
	fetch "$BASE_URL/download/tools/$SPHINCS_TOOL"    "$TMP/sphincs-verify" || die "could not fetch $SPHINCS_TOOL"

	PUB_ACTUAL="$(sha256sum "$TMP/release.pub" | awk '{print $1}')"
	[ "$PUB_ACTUAL" = "$RELEASE_PUBKEY_SHA256" ] || die "release public key hash mismatch (expected $RELEASE_PUBKEY_SHA256, got $PUB_ACTUAL) — refusing to install"

	TOOL_ACTUAL="$(sha256sum "$TMP/sphincs-verify" | awk '{print $1}')"
	[ "$TOOL_ACTUAL" = "$SPHINCS_TOOL_SHA256" ] || die "sphincs-verify tool hash mismatch (expected $SPHINCS_TOOL_SHA256, got $TOOL_ACTUAL) — refusing to install"

	chmod +x "$TMP/sphincs-verify"
	"$TMP/sphincs-verify" \
		--public-key "$TMP/release.pub" \
		--signature "$TMP/${MANIFEST}.sig" \
		--message "$TMP/$MANIFEST" >/dev/null \
		|| die "SLH-DSA signature verification FAILED for $MANIFEST — refusing to install"
	say "SLH-DSA signature valid."
else
	warn "SLH-DSA signature verification skipped — trust anchors not pinned in this installer build (pre-release only; SHA-256 check still applies)"
fi

say "Verifying checksum..."
EXPECT="$(grep " ${TARBALL}\$" "$TMP/$MANIFEST" | awk '{print $1}')"
[ -n "$EXPECT" ] || die "no checksum for ${TARBALL} in $MANIFEST"
ACTUAL="$(sha256sum "$TMP/$TARBALL" | awk '{print $1}')"
[ "$EXPECT" = "$ACTUAL" ] || die "checksum mismatch — refusing to install (expected $EXPECT, got $ACTUAL)"

say "Installing..."
tar -xzf "$TMP/$TARBALL" -C "$TMP"
SRC="$(find "$TMP" -type f -path '*/bin/secria-vpn' -perm -u+x | head -n1)"
[ -n "$SRC" ] || SRC="$(find "$TMP" -type f -name secria-vpn -perm -u+x | head -n1)"
[ -n "$SRC" ] || die "binary not found in archive"
SRC_ROOT="$(dirname "$(dirname "$SRC")")"

# One install path, always the tarball's own installer: a second copy of it here drifted, and
# the copy was the one that silently skipped the AppArmor override and the dependency check.
[ -x "$SRC_ROOT/install.sh" ] || die "the archive has no install.sh — refusing to install by hand"
if [ -n "${SECRIA_BIN_DIR:-}" ]; then
	SECRIA_BIN_DIR="$SECRIA_BIN_DIR" "$SRC_ROOT/install.sh"
else
	"$SRC_ROOT/install.sh"
fi
