#!/usr/bin/env bash
# Cerynix — clone-free on-prem bootstrap
# Copyright (c) 2026 SIA Cerynix. All rights reserved.
# Proprietary and confidential.
# SPDX-License-Identifier: LicenseRef-Cerynix-Proprietary
#
# Fetches the Cerynix on-prem bundle from the self-hosted download endpoint,
# verifies it, unpacks it, and hands off to the bundled ./install.sh — so a
# client can install with ONE line and no repository access:
#
#   curl -fsSL https://<download-host>/ | bash
#   curl -fsSL https://<download-host>/ | bash -s -- --hostname cerynix.acme.eu ...
#
# Any flags after `bash -s --` are passed straight through to install.sh.
#
# The download host is baked into this script by the Worker that serves it. To
# run a saved copy against a specific endpoint, set CERYNIX_DL:
#   CERYNIX_DL=https://dl.acme.internal ./get.sh
#
# Other overrides: CERYNIX_BUNDLE (bundle filename), CERYNIX_HOME (install dir).
set -euo pipefail

# ---------- config ----------
# __CERYNIX_DL__ is rewritten to the serving origin (e.g. https://dl.acme.eu) by
# the download Worker. An un-substituted copy requires CERYNIX_DL to be set.
DL_DEFAULT="https://dl.cerynix.com"
CERYNIX_DL="${CERYNIX_DL:-$DL_DEFAULT}"
BUNDLE_NAME="${CERYNIX_BUNDLE:-cerynix-onprem.tar.gz}"

# ---------- pretty output (to stderr, so stdout stays clean) ----------
if [ -t 2 ]; then
  B=$'\033[1m'; G=$'\033[32m'; Y=$'\033[33m'; R=$'\033[31m'; C=$'\033[36m'; N=$'\033[0m'
else
  B=""; G=""; Y=""; R=""; C=""; N=""
fi
say() { printf '%s\n' "${C}==>${N} ${B}$*${N}" >&2; }
ok()  { printf '%s\n' "  ${G}OK${N} $*" >&2; }
die() { printf '%s\n' "${R}ERROR:${N} $*" >&2; exit 1; }

# ---------- validate the download host ----------
case "$CERYNIX_DL" in
  ""|*__CERYNIX_DL__*)
    die "download host is not set. Run via the hosted URL (curl -fsSL https://<host>/ | bash) or set CERYNIX_DL=https://<host>." ;;
  http://*|https://*) : ;;
  *) die "CERYNIX_DL must start with http:// or https:// (got: $CERYNIX_DL)" ;;
esac
CERYNIX_DL="${CERYNIX_DL%/}"
URL="${CERYNIX_DL}/${BUNDLE_NAME}"

# ---------- prerequisites ----------
command -v curl >/dev/null 2>&1 || die "curl is required but not installed."
command -v tar  >/dev/null 2>&1 || die "tar is required but not installed."
command -v gzip >/dev/null 2>&1 || die "gzip is required but not installed."

say "Cerynix on-prem bootstrap"

# ---------- staging temp dir (auto-cleaned) ----------
STAGE="$(mktemp -d "${TMPDIR:-/tmp}/cerynix-XXXXXX")" || die "could not create a temporary directory."
trap 'rm -rf "$STAGE"' EXIT INT TERM
TARBALL="${STAGE}/bundle.tar.gz"

# ---------- download ----------
say "Downloading bundle from ${URL}"
if ! curl -fsSL --retry 3 --connect-timeout 20 -o "$TARBALL" "$URL" 2>"${STAGE}/curl.err"; then
  detail="$(tr -d '\r' <"${STAGE}/curl.err" | tail -n1)"
  die "download failed from ${URL}${detail:+ — $detail}"
fi
[ -s "$TARBALL" ] || die "downloaded file is empty — is the bundle uploaded to the endpoint?"
ok "downloaded $(wc -c <"$TARBALL" | tr -d ' ') bytes"

# ---------- verify it is a real gzip tar ----------
say "Verifying archive integrity"
gzip -t "$TARBALL" 2>/dev/null || die "downloaded file is not a valid gzip archive (corrupt download or wrong URL)."
tar -tzf "$TARBALL" >/dev/null 2>&1 || die "gzip is valid but the tar contents could not be read."
ok "archive is a valid gzip tar"

# ---------- extract into a persistent install directory ----------
DEST="${CERYNIX_HOME:-$(pwd)/cerynix-onprem}"
say "Extracting into ${DEST}"
mkdir -p "$DEST" || die "cannot create install directory ${DEST}."
tar -xzf "$TARBALL" -C "$DEST" || die "extraction failed."

# The bundle may extract flat or under a single top-level directory; locate the
# installer either way.
INSTALL="$(find "$DEST" -maxdepth 2 -name install.sh -type f 2>/dev/null | head -n1)"
[ -n "$INSTALL" ] || die "install.sh not found inside the bundle (unexpected archive layout)."
RUN_DIR="$(cd "$(dirname "$INSTALL")" && pwd)"
chmod +x "$INSTALL" 2>/dev/null || true
ok "bundle ready in ${RUN_DIR}"

# ---------- hand off to the installer ----------
# Drop the staging dir now and disable the trap: exec replaces this process, so
# the trap would never fire, and RUN_DIR must survive for the installer to use.
rm -rf "$STAGE"
trap - EXIT INT TERM
cd "$RUN_DIR" || die "cannot enter ${RUN_DIR}."
say "Handing off to the installer"
exec ./install.sh "$@"
