#!/usr/bin/env bash
# Hostpilot bootstrap installer
# Usage: curl -fsSL https://get.hp.iphost24.net | sudo bash
set -euo pipefail

if [ "$(id -u)" -ne 0 ]; then
    echo "Bitte als root ausführen (sudo bash)" >&2
    exit 1
fi

. /etc/os-release
case "${ID}:${VERSION_ID}" in
    debian:12|debian:13|ubuntu:24.04|ubuntu:26.04)
        echo "→ Unterstütztes System erkannt: ${PRETTY_NAME}"
        ;;
    *)
        echo "✗ Nicht unterstütztes System: ${PRETTY_NAME}" >&2
        echo "Unterstützt: Debian 12/13, Ubuntu 24.04/26.04" >&2
        exit 1
        ;;
esac

REPO_URL="${HOSTPILOT_REPO_URL:-https://apt.hp.iphost24.net}"
CHANNEL="${HOSTPILOT_CHANNEL:-stable}"   # stable | beta
KEYRING="/etc/apt/keyrings/hostpilot.gpg"

apt-get update -qq
apt-get install -y -qq curl ca-certificates gnupg

install -m 0755 -d /etc/apt/keyrings
curl -fsSL "${REPO_URL}/hostpilot.gpg" | gpg --dearmor -o "${KEYRING}"
chmod 0644 "${KEYRING}"

echo "deb [signed-by=${KEYRING}] ${REPO_URL} ${CHANNEL} main" > /etc/apt/sources.list.d/hostpilot.list

apt-get update -qq
apt-get install -y hostpilot-api hostpilot-agent hostpilot-ui

echo "→ Version: $(hostpilot-api --version 2>/dev/null || echo '?')"

# Stack einrichten (Nginx/Apache/Postfix/Dovecot/PowerDNS/DB/restic/...).
# Der Provisioner wird vom hostpilot-api-Paket nach /usr/share/hostpilot/provision.sh
# mitgeliefert; bei fehlendem Pfad als No-op überspringen.
PROVISION="/usr/share/hostpilot/provision.sh"
if [ -x "$PROVISION" ]; then
    echo "→ Provisioning (Stack einrichten) …"
    bash "$PROVISION" || echo "⚠ Provisioning teilweise fehlgeschlagen — Log prüfen."
fi

systemctl enable --now hostpilot-agent hostpilot-api hostpilot-ui

echo ""
echo "✓ Hostpilot installiert (Kanal: ${CHANNEL})."
echo "  Panel:  http://$(hostname -f)"
echo "  Logs:   journalctl -u hostpilot-api -u hostpilot-agent -u hostpilot-ui -f"
