#!/bin/sh
# MaxPanel one-shot installer.
#
# Usage on a fresh Ubuntu 24.04 box:
#   curl -fsSL https://get.maxpanel.cenmax.in | sh
#   curl -fsSL https://get.maxpanel.cenmax.in | 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 prints the
#      next steps the operator needs to take.
#
# Anything beyond that — entering the license, pointing DNS, getting
# certbot to issue a panel cert — is in the postinst summary or in
# docs/install.md.
set -eu

REPO_URL="${MAXPANEL_REPO_URL:-https://apt.maxpanel.cenmax.in}"
KEY_URL="${MAXPANEL_KEY_URL:-${REPO_URL}/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 "=== MaxPanel install complete ==="
echo "Run \`systemctl status ${PACKAGE%-mail}-agent\` to confirm the agent is running."
echo "See the package summary printed above for the next steps."
