#!/bin/bash
#
# Eldric AI OS — one-liner bootstrap
#
# Usage:
#   curl -fsSL https://repo.eldric.ai/install-eldric.sh | sudo bash
#
# With options (you must use -s -- to separate bash args from script args):
#   curl -fsSL https://repo.eldric.ai/install-eldric.sh | \
#       sudo bash -s -- --license /tmp/license.json --admin-email me@example.com
#
# Flow:
#   1. Check root + supported distro
#   2. Add the dnf repo via setup-dnf-repo.sh (inline if not yet on disk)
#   3. dnf install -y eldric-aios
#   4. systemctl enable --now eldric-aios
#   5. Hand off remaining args to `eldric setup` (C++ post-install logic:
#      health wait, license activation, admin setup, summary)
#
# Refuses if /var/lib/eldric exists — that's an upgrade case, route via
# `eldric upgrade` (not yet implemented; today it's still manual dnf upgrade).

set -euo pipefail

readonly SETUP_REPO_URL="https://repo.eldric.ai/install.sh"

info() { printf '==> %s\n' "$*"; }
die()  { printf '==> ERROR: %s\n' "$*" >&2; exit 1; }

[[ "$(id -u)" -eq 0 ]] || die "must run as root. Try: curl -fsSL ${SETUP_REPO_URL/install.sh/install-eldric.sh} | sudo bash"

# Upgrade guard: data dir present means a previous install exists.
if [[ -d /var/lib/eldric ]] || [[ -d /data/eldric/controller ]]; then
    die "/var/lib/eldric or /data/eldric/controller already exists — this looks like an upgrade.
        Use 'sudo dnf upgrade eldric-aios' to upgrade, or 'sudo dnf reinstall eldric-aios' to repair.
        First-time bootstrap refuses to run when state is already present."
fi

info "step 1/5: add dnf repo"
# Run setup via curl-pipe-bash; trusted because we're already trusting *this* script.
curl -fsSL --max-time 30 "$SETUP_REPO_URL" | bash

info "step 2/5: install eldric-aios"
dnf install -y eldric-aios

info "step 3/5: enable systemd unit"
systemctl daemon-reload
systemctl enable --now eldric-aios

info "step 4/5: wait for daemon ready + run post-install (eldric setup)"
if ! command -v eldric >/dev/null 2>&1; then
    die "'eldric' CLI not on PATH after dnf install; check /usr/bin/eldric exists"
fi

# Hand off remaining argv to the C++ subcommand. It handles license activation,
# admin-exists check, health wait, summary print. Failures there don't damage
# the install — operator can re-run 'eldric setup' standalone.
info "step 5/5: hand off to 'eldric setup'"
exec eldric setup "$@"
