#!/usr/bin/env bash
# ScalPanel installer (ADR-0063): an all-in-one server on Ubuntu 22.04/24.04 or
# Debian 12/13 (x86_64).
#
#   curl -fsSL https://scalpanel.scalws.com/install.sh | sudo bash
#
# Settings come from the environment, or are asked for:
#   SCALPANEL_HOSTNAME     the server's name (e.g. panel.example.com)
#   SCALPANEL_PUBLIC_IP    its public IPv4 address (detected)
#   SCALPANEL_ADMIN_EMAIL  for certificates and notices
#   SCALPANEL_YES=1        no questions (needs the three settings above)
#
# Everything downloaded is verified against the release key below before it
# is used.
set -euo pipefail
# Settings by their names from before the rename (VPANEL_*, ADR-0201).
for _v in $(compgen -v VPANEL_); do
  _n=SCALPANEL_${_v#VPANEL_}
  [ -n "${!_n:-}" ] || export "$_n=${!_v}"
done

RELEASE_PUBLIC_KEY="sprk1.QUorqm4dmqc5VKSD6_KfNN9erY0Go0bhP2NcrIYNilA"
UPDATE_URL="${SCALPANEL_UPDATE_URL:-https://scalpanel.scalws.com}"
CHANNEL="${SCALPANEL_UPDATE_CHANNEL:-stable}"

say() { printf '\033[1m==>\033[0m %s\n' "$*"; }
die() { printf '\033[31merror:\033[0m %s\n' "$*" >&2; exit 1; }
ask() { # var prompt default
  local v=${!1:-}
  if [ -z "$v" ]; then
    [ "${SCALPANEL_YES:-0}" = 1 ] && die "$1 is required"
    [ -r /dev/tty ] || die "$1 is required (no terminal to ask)"
    printf '%s [%s]: ' "$2" "$3" > /dev/tty
    read -r v < /dev/tty || true
    v=${v:-$3}
  fi
  [ -n "$v" ] || die "$1 is required"
  printf -v "$1" '%s' "$v"
  export "${1?}"
}

# ---------------------------------------------------------------- checks
[ "$(id -u)" = 0 ] || die "run as root (sudo bash)"
[ "$(uname -m)" = x86_64 ] || die "ScalPanel needs an x86_64 server"
[ -r /etc/os-release ] || die "unknown operating system"
# shellcheck disable=SC1091
. /etc/os-release
case "$ID:${VERSION_ID:-}" in
  ubuntu:22.04|ubuntu:24.04|debian:12|debian:13) OS_FAMILY=debian ;;
  # ADR-0234: the RHEL family, 9 and 10.
  almalinux:9*|almalinux:10*|rocky:9*|rocky:10*) OS_FAMILY=rhel ;;
  *) die "supported: Ubuntu 22.04/24.04, Debian 12/13, AlmaLinux and Rocky Linux 9/10 (this is $PRETTY_NAME)" ;;
esac
command -v systemctl >/dev/null || die "systemd is required"
for f in /etc/scalpanel/version /etc/scalpanel/version; do
  [ -e "$f" ] && die "ScalPanel $(cat "$f") is already installed; update it with: scalpanelctl update"
done
mem_kb=$(awk '/MemTotal/{print $2}' /proc/meminfo)
[ "$mem_kb" -ge 3500000 ] || say "warning: $((mem_kb / 1024)) MiB of memory; 4 GiB or more is recommended"
avail_kb=$(df -Pk /var/lib | awk 'NR==2{print $4}')
[ "$avail_kb" -ge 20000000 ] || die "at least 20 GB of free disk space is needed in /var/lib"
busy=""
for p in 21 25 80 110 443 465 587 993 995 2078 2080 2083 2087 2092 2096 2222 $(seq 13306 13315) $(seq 15432 15441) $(seq 37017 37026) $(seq 30000 30049); do
  ss -Hltn "sport = :$p" 2>/dev/null | grep -q . && busy="$busy $p"
done
[ -z "$busy" ] || die "these ports are in use:$busy (ScalPanel needs a server without other web or mail services)"
# The published MongoDB ports lie in the kernel's ephemeral range: an
# outgoing connection could take one and Docker could not publish it (seen
# as "37020: address already in use"). They are reserved for ScalPanel.
printf 'net.ipv4.ip_local_reserved_ports = 37017-37026\n' > /etc/sysctl.d/90-scalpanel-ports.conf
sysctl -q -w net.ipv4.ip_local_reserved_ports=37017-37026 || true

# ---------------------------------------------------------------- packages
say "installing packages"
if [ "$OS_FAMILY" = rhel ]; then
  # SELinux and firewalld stay as they are (ADR-0234 addendum): the containers
  # are confined (container_t) once Docker labels them, and firewalld gets
  # ScalPanel's ports, below.
  dnf install -y -q --allowerasing ca-certificates curl openssl jq iproute openssh-clients >/dev/null
  if ! command -v docker >/dev/null || ! docker compose version >/dev/null 2>&1; then
    say "installing Docker"
    curl -fsSL https://download.docker.com/linux/rhel/docker-ce.repo -o /etc/yum.repos.d/docker-ce.repo
    dnf install -y -q docker-ce docker-ce-cli containerd.io docker-compose-plugin >/dev/null
  fi
  # SELinux (ADR-0234 addendum): Docker labels the containers (container_t)
  # and the host directories they mount are container_file_t; the node runs
  # privileged (spc_t). Checked enforcing on AlmaLinux 9.8 with no denials.
  if command -v getenforce >/dev/null && [ "$(getenforce)" != Disabled ]; then
    say "labelling ScalPanel's directories for SELinux"
    dnf install -y -q container-selinux policycoreutils-python-utils >/dev/null
    for d in /etc/scalpanel /var/lib/scalpanel /opt/scalpanel /srv/scalpanel; do
      semanage fcontext -a -t container_file_t "$d(/.*)?" 2>/dev/null || semanage fcontext -m -t container_file_t "$d(/.*)?"
      mkdir -p "$d"
      restorecon -R "$d"
    done
    # The link to the nodes is read by the host's wg-quick and nft only.
    semanage fcontext -a -t etc_t "/etc/scalpanel/link(/.*)?" 2>/dev/null || true
    mkdir -p /etc/docker
    if [ -s /etc/docker/daemon.json ]; then
      jq '. + {"selinux-enabled": true}' /etc/docker/daemon.json > /etc/docker/daemon.json.new
      mv /etc/docker/daemon.json.new /etc/docker/daemon.json
    else
      printf '{"selinux-enabled": true}\n' > /etc/docker/daemon.json
    fi
    # A running Docker reads it only when it starts.
    ! systemctl is-active -q docker || systemctl restart docker
  fi
  # firewalld stays on when it runs (ADR-0234 addendum): the server's SSH
  # ports first (never lock the operator out), then ScalPanel's services, the
  # nodes' link (UDP 51820) and the replica link (UDP 51821). Admin -> Firewall
  # still filters by address in its own nftables tables.
  if systemctl is-active -q firewalld 2>/dev/null; then
    say "opening ScalPanel's ports in firewalld"
    for p in $( (sshd -T 2>/dev/null || true) | awk '$1 == "port" {print $2}') 22; do
      firewall-cmd -q --permanent --add-port="$p/tcp"
    done
    for p in 21/tcp 25/tcp 53/tcp 53/udp 80/tcp 110/tcp 443/tcp 443/udp 465/tcp 587/tcp 993/tcp 995/tcp 2078/tcp 2080/tcp \
      2083/tcp 2087/tcp 2092/tcp 2096/tcp 2222/tcp 13306-13315/tcp 15432-15441/tcp 30000-30049/tcp 37017-37026/tcp \
      51820/udp 51821/udp; do
      firewall-cmd -q --permanent --add-port="$p"
    done
    firewall-cmd -q --reload
  fi
else
  export DEBIAN_FRONTEND=noninteractive
  apt-get -o DPkg::Lock::Timeout=600 update -qq
  apt-get -o DPkg::Lock::Timeout=600 install -y -qq ca-certificates curl openssl jq iproute2 openssh-client >/dev/null
  if ! command -v docker >/dev/null || ! docker compose version >/dev/null 2>&1; then
    say "installing Docker"
    install -m 0755 -d /etc/apt/keyrings
    curl -fsSL "https://download.docker.com/linux/$ID/gpg" -o /etc/apt/keyrings/docker.asc
    chmod a+r /etc/apt/keyrings/docker.asc
    echo "deb [arch=amd64 signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/$ID $VERSION_CODENAME stable" \
      > /etc/apt/sources.list.d/docker.list
    apt-get -o DPkg::Lock::Timeout=600 update -qq
    apt-get -o DPkg::Lock::Timeout=600 install -y -qq docker-ce docker-ce-cli containerd.io docker-compose-plugin >/dev/null
  fi
fi
systemctl enable --now docker >/dev/null

# ---------------------------------------------------------------- settings
detected_ip=$(ip -4 route get 1.1.1.1 2>/dev/null | awk '{for (i = 1; i < NF; i++) if ($i == "src") print $(i + 1)}' | head -1)
ask SCALPANEL_HOSTNAME "Server name (a DNS name pointing to this server)" "$(hostname -f 2>/dev/null || hostname)"
ask SCALPANEL_PUBLIC_IP "Public IPv4 address" "$detected_ip"
ask SCALPANEL_ADMIN_EMAIL "Administrator email" "admin@$SCALPANEL_HOSTNAME"
[[ "$SCALPANEL_HOSTNAME" =~ ^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)+$ ]] ||
  die "$SCALPANEL_HOSTNAME is not a DNS name"
[[ "$SCALPANEL_PUBLIC_IP" =~ ^[0-9]{1,3}(\.[0-9]{1,3}){3}$ ]] || die "$SCALPANEL_PUBLIC_IP is not an IPv4 address"
[[ "$SCALPANEL_ADMIN_EMAIL" =~ ^[^@[:space:]]+@[^@[:space:]]+\.[^@[:space:]]+$ ]] || die "$SCALPANEL_ADMIN_EMAIL is not an email address"

# ---------------------------------------------------------------- the release
WORK=$(mktemp -d); trap 'rm -rf "$WORK"' EXIT
b64=$(printf '%s' "${RELEASE_PUBLIC_KEY#*.}" | tr '_-' '/+')
while [ $(( ${#b64} % 4 )) -ne 0 ]; do b64="$b64="; done
printf -- '-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEA%s\n-----END PUBLIC KEY-----\n' "$b64" > "$WORK/release.pem"
# Plain HTTP only for testing (SCALPANEL_ALLOW_HTTP=1); the signatures protect
# the content either way.
proto="=https"
[ "${SCALPANEL_ALLOW_HTTP:-0}" = 1 ] && proto="=http,https"
fetch() { curl -fsSL --proto "$proto" --retry 3 --connect-timeout 20 -o "$2" "$UPDATE_URL/$1"; }
fetch_signed() {
  fetch "$1" "$2" && fetch "$1.sig" "$2.sig" || die "cannot download $UPDATE_URL/$1"
  base64 -d "$2.sig" > "$WORK/sig.bin"
  openssl pkeyutl -verify -pubin -inkey "$WORK/release.pem" -rawin -in "$2" -sigfile "$WORK/sig.bin" >/dev/null 2>&1 ||
    die "the signature of $1 does not verify: refusing to install"
}
say "reading the $CHANNEL release channel"
fetch_signed "channels/$CHANNEL.json" "$WORK/channel.json"
[ "$(jq -r .channel "$WORK/channel.json")" = "$CHANNEL" ] || die "the $CHANNEL channel file names another channel"
rel=$(jq -er .release "$WORK/channel.json")
case "$rel" in *..*|/*|*://*) die "invalid release path" ;; esac
fetch_signed "$rel" "$WORK/release.json"
version=$(jq -er .version "$WORK/release.json")
say "ScalPanel $version"
fetch "$(jq -er .bundle.path "$WORK/release.json")" "$WORK/bundle.tar.gz" || die "cannot download the bundle"
[ "$(sha256sum "$WORK/bundle.tar.gz" | cut -d' ' -f1)" = "$(jq -er .bundle.sha256 "$WORK/release.json")" ] ||
  die "the bundle does not match the signed release"
mkdir -p "$WORK/bundle"
tar -xzf "$WORK/bundle.tar.gz" -C "$WORK/bundle" --no-same-owner

# scalpanelctl downloads and verifies the release again (with the same key),
# fetches the images and sets everything up.
say "installing ScalPanel $version (this takes a few minutes)"
SCALPANEL_VERSION=$version SCALPANEL_UPDATE_URL=$UPDATE_URL SCALPANEL_UPDATE_CHANNEL=$CHANNEL \
  bash "$WORK/bundle/bin/scalpanelctl" install
