#!/usr/bin/env bash
# get.vpanel.sh - bootstrap installer for vpanel control-plane hosts.
# Phase 6 Workstream 5 §6.8 one-liner. Detects distro, adds the signed
# vpanel repository, installs the base vpanel package, and hands off
# to vpanel-install + vpanel-init. All real lifecycle logic lives in
# the packaged binaries; keep this file small and auditable.
#
# Usage:
#   curl -sSL https://get.vpanel.sh | sudo bash
#   curl -sSL https://get.vpanel.sh | sudo bash -s -- --profile control-plane --channel rc --yes

set -euo pipefail

PROFILE="all-in-one"
CHANNEL="stable"
ASSUME_YES="0"
KEY_URL="${VPANEL_BOOTSTRAP_KEY_URL:-https://get.vpanel.sh/keys/vpanel-release.gpg}"
KEYRING="${VPANEL_BOOTSTRAP_KEYRING:-/usr/share/keyrings/vpanel-release.gpg}"
APT_HOST="${VPANEL_BOOTSTRAP_APT_HOST:-https://repo.vpanel.sh}"
DNF_HOST="${VPANEL_BOOTSTRAP_DNF_HOST:-https://repo.vpanel.sh}"
APT_LIST="${VPANEL_BOOTSTRAP_APT_LIST:-/etc/apt/sources.list.d/vpanel.list}"
DNF_REPO="${VPANEL_BOOTSTRAP_DNF_REPO:-/etc/yum.repos.d/vpanel.repo}"
OS_RELEASE_FILE="${VPANEL_BOOTSTRAP_OS_RELEASE:-/etc/os-release}"

log() { printf '[vpanel] %s\n' "$*"; }
die() { printf '[vpanel] error: %s\n' "$*" >&2; exit 1; }

start_control_plane_daemon() {
    case "$PROFILE" in
        all-in-one|control-plane) ;;
        *) return 0 ;;
    esac
    if [ "${VPANEL_BOOTSTRAP_SYSTEMD:-}" = "1" ]; then
        :
    elif ! command -v systemctl >/dev/null 2>&1 || [ ! -d /run/systemd/system ]; then
        log "systemd not detected; skip automatic vpaneld start"
        return 0
    fi
    log "starting vpaneld.service"
    systemctl daemon-reload
    systemctl start vpaneld.service
}

while [ "$#" -gt 0 ]; do
    case "$1" in
        --profile)   PROFILE="${2:?}"; shift 2 ;;
        --profile=*) PROFILE="${1#*=}"; shift ;;
        --channel)   CHANNEL="${2:?}"; shift 2 ;;
        --channel=*) CHANNEL="${1#*=}"; shift ;;
        --yes|-y)    ASSUME_YES="1"; shift ;;
        -h|--help)   sed -n '2,10p' "$0"; exit 0 ;;
        *)           die "unknown flag: $1" ;;
    esac
done

case "$PROFILE" in
    all-in-one|control-plane|app-host|mail-host|database-host|custom) ;;
    *) die "unsupported profile: $PROFILE" ;;
esac
case "$CHANNEL" in stable|rc) ;; *) die "unsupported channel: $CHANNEL" ;; esac

effective_uid="${EUID:-$(id -u)}"
if [ "${VPANEL_BOOTSTRAP_FORCE_ROOT:-0}" = "1" ]; then
    effective_uid="0"
fi
if [ "$effective_uid" != "0" ]; then
    log "re-executing under sudo"
    ARGS=( --profile "$PROFILE" --channel "$CHANNEL" )
    [ "$ASSUME_YES" = "1" ] && ARGS+=( --yes )
    exec sudo -E bash "$0" "${ARGS[@]}"
fi

[ -r "$OS_RELEASE_FILE" ] || die "$OS_RELEASE_FILE missing; cannot detect distro"
# shellcheck disable=SC1091
. "$OS_RELEASE_FILE"
DISTRO_ID="${VPANEL_BOOTSTRAP_DISTRO_ID:-${ID:-unknown}}"
DISTRO_LIKE="${VPANEL_BOOTSTRAP_DISTRO_LIKE:-${ID_LIKE:-}}"
CODENAME="${VPANEL_BOOTSTRAP_CODENAME:-${VERSION_CODENAME:-stable}}"
PKG="${VPANEL_BOOTSTRAP_PKG:-}"

if [ -z "$PKG" ]; then
    if command -v apt-get >/dev/null 2>&1 && { [ "$DISTRO_ID" = "ubuntu" ] || [ "$DISTRO_ID" = "debian" ] || [[ "$DISTRO_LIKE" == *debian* ]]; }; then
        PKG="apt"
    elif command -v dnf >/dev/null 2>&1 && { [ "$DISTRO_ID" = "rocky" ] || [ "$DISTRO_ID" = "almalinux" ] || [ "$DISTRO_ID" = "rhel" ] || [[ "$DISTRO_LIKE" == *rhel* ]]; }; then
        PKG="dnf"
    else
        die "unsupported distro: ${DISTRO_ID} (${PRETTY_NAME:-unknown}). See https://docs.vpanel.sh/install"
    fi
fi

log "distro=$DISTRO_ID pkg=$PKG profile=$PROFILE channel=$CHANNEL"

fetch_key() {
    log "fetching signing key from $KEY_URL"
    install -d -m 0755 "$(dirname "$KEYRING")"
    if command -v curl >/dev/null 2>&1; then curl -fsSL "$KEY_URL" -o "$KEYRING"
    elif command -v wget >/dev/null 2>&1; then wget -qO "$KEYRING" "$KEY_URL"
    else die "need curl or wget"; fi
    chmod 0644 "$KEYRING"
}

add_apt_repo() {
    local list="$APT_LIST"
    log "adding apt repo for $DISTRO_ID $CODENAME $CHANNEL"
    install -d -m 0755 "$(dirname "$list")"
    printf 'deb [signed-by=%s] %s/%s %s %s\n' \
        "$KEYRING" "$APT_HOST" "$DISTRO_ID" "$CODENAME" "$CHANNEL" > "$list"
    chmod 0644 "$list"
    apt-get update -y
    apt-get install -y "vpanel"
}

add_dnf_repo() {
    local repo="$DNF_REPO"
    log "adding dnf repo for $DISTRO_ID $CHANNEL"
    install -d -m 0755 "$(dirname "$repo")"
    cat > "$repo" <<EOF
[vpanel-${CHANNEL}]
name=vpanel ${CHANNEL}
baseurl=${DNF_HOST}/${DISTRO_ID}/\$releasever/${CHANNEL}/\$basearch
enabled=1
gpgcheck=0
repo_gpgcheck=1
gpgkey=${KEY_URL}
EOF
    chmod 0644 "$repo"
    dnf -y makecache
    dnf install -y "vpanel"
}

fetch_key
case "$PKG" in apt) add_apt_repo ;; dnf) add_dnf_repo ;; esac

log "running vpanel-install"
INSTALL_ARGS=( --profile "$PROFILE" --install-packages )
[ "$ASSUME_YES" = "1" ] && INSTALL_ARGS+=( --yes )
vpanel-install "${INSTALL_ARGS[@]}" apply

log "handing off to vpanel-init wizard"
if [ "$ASSUME_YES" = "1" ] || ! [ -t 0 ]; then
    vpanel-init --profile "$PROFILE" --yes wizard
else
    vpanel-init --profile "$PROFILE" wizard
fi

start_control_plane_daemon

case "$PROFILE" in
    all-in-one|control-plane)
        log "done. next: bootstrap the first operator with vpanel-init claim --email admin@example.com --name admin --password '<strong-password>'"
        ;;
    *)
        log "done. next: register this host from the control plane and enroll vpanel-agent with the issued token"
        ;;
esac
