#!/bin/sh
# MaxPanel one-shot installer.
#
# Usage on a fresh Ubuntu 24.04 box:
#   curl -fsSL https://get.maxpanel.net | sh
#   curl -fsSL https://get.maxpanel.net | MAXPANEL_FLAVOR=mail sh   # mail node
#
# What it does:
#   1. Verifies we're on Ubuntu 24.04 (Noble). Anything else aborts.
#   2. Adds the MaxPanel APT repo + GPG key.
#   3. apt-get update && apt-get install -y maxpanel  (or maxpanel-mail).
#   4. Hands control to the package's postinst, which creates the
#      admin account, prints the credentials, and tells the operator
#      how to enter their license token.
set -eu

REPO_URL="${MAXPANEL_REPO_URL:-https://apt.maxpanel.net}"
# The GPG key is served from the install-script host (get.*) by the
# licensing-host setup script; mirroring it to apt.* is optional and
# not relied on. Override via MAXPANEL_KEY_URL if you've moved it.
KEY_URL="${MAXPANEL_KEY_URL:-https://get.maxpanel.net/maxpanel.gpg}"
FLAVOR="${MAXPANEL_FLAVOR:-main}"   # "main" or "mail"

case "$FLAVOR" in
  main) PACKAGE="maxpanel" ;;
  mail) PACKAGE="maxpanel-mail" ;;
  *) echo "MAXPANEL_FLAVOR must be 'main' or 'mail' (got: $FLAVOR)" >&2; exit 2 ;;
esac

if [ "$(id -u)" -ne 0 ]; then
  echo "This installer must run as root (try: sudo sh -)" >&2
  exit 1
fi

# 1. OS check -------------------------------------------------------
. /etc/os-release
if [ "${ID:-}" != "ubuntu" ] || [ "${VERSION_CODENAME:-}" != "noble" ]; then
  cat >&2 <<EOF
MaxPanel only supports Ubuntu 24.04 (Noble Numbat).
  Detected: ${PRETTY_NAME:-unknown}
If you really know what you're doing, set MAXPANEL_SKIP_OS_CHECK=1 and re-run.
EOF
  if [ -z "${MAXPANEL_SKIP_OS_CHECK:-}" ]; then
    exit 1
  fi
fi

# 2. APT repo + key -------------------------------------------------
apt-get update -y
apt-get install -y curl gnupg ca-certificates apt-transport-https

install -d -m 0755 /etc/apt/keyrings
curl -fsSL "$KEY_URL" | gpg --dearmor --yes -o /etc/apt/keyrings/maxpanel.gpg
chmod 0644 /etc/apt/keyrings/maxpanel.gpg

cat > /etc/apt/sources.list.d/maxpanel.sources <<EOF
Types: deb
URIs: ${REPO_URL}
Suites: noble
Components: main
Signed-By: /etc/apt/keyrings/maxpanel.gpg
EOF

apt-get update -y

# 3. Install --------------------------------------------------------
DEBIAN_FRONTEND=noninteractive apt-get install -y "$PACKAGE"

echo
echo "All package output is above. Scroll up if you missed the admin"
echo "credentials or the URL — they are printed once."
