#!/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://vpanel.scb.network/install.sh | sudo bash
#
# Settings come from the environment, or are asked for:
#   VPANEL_HOSTNAME     the server's name (e.g. panel.example.com)
#   VPANEL_PUBLIC_IP    its public IPv4 address (detected)
#   VPANEL_ADMIN_EMAIL  for certificates and notices
#   VPANEL_VERSION      a specific release (default: the latest)
#   VPANEL_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

RELEASE_PUBLIC_KEY="vprk1.QUorqm4dmqc5VKSD6_KfNN9erY0Go0bhP2NcrIYNilA"
UPDATE_URL="${VPANEL_UPDATE_URL:-https://vpanel.scb.network}"
CHANNEL="${VPANEL_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
    [ "${VPANEL_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) ;;
  *) die "supported: Ubuntu 22.04/24.04, Debian 12/13 (this is $PRETTY_NAME)" ;;
esac
command -v systemctl >/dev/null || die "systemd is required"
for f in /etc/scalpanel/version /etc/vpanel/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 25 80 443 587 993 2078 2080 2083 2087 2096 2222 $(seq 13306 13315) $(seq 15432 15441) $(seq 37017 37026); 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)"

# ---------------------------------------------------------------- packages
say "installing packages"
export DEBIAN_FRONTEND=noninteractive
apt-get update -qq
apt-get 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 update -qq
  apt-get install -y -qq docker-ce docker-ce-cli containerd.io docker-compose-plugin >/dev/null
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 VPANEL_HOSTNAME "Server name (a DNS name pointing to this server)" "$(hostname -f 2>/dev/null || hostname)"
ask VPANEL_PUBLIC_IP "Public IPv4 address" "$detected_ip"
ask VPANEL_ADMIN_EMAIL "Administrator email" "admin@$VPANEL_HOSTNAME"
[[ "$VPANEL_HOSTNAME" =~ ^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)+$ ]] ||
  die "$VPANEL_HOSTNAME is not a DNS name"
[[ "$VPANEL_PUBLIC_IP" =~ ^[0-9]{1,3}(\.[0-9]{1,3}){3}$ ]] || die "$VPANEL_PUBLIC_IP is not an IPv4 address"
[[ "$VPANEL_ADMIN_EMAIL" =~ ^[^@[:space:]]+@[^@[:space:]]+\.[^@[:space:]]+$ ]] || die "$VPANEL_ADMIN_EMAIL is not an email address"

# ---------------------------------------------------------------- the release
WORK=$(mktemp -d); trap 'rm -rf "$WORK"' EXIT
b64=$(printf '%s' "${RELEASE_PUBLIC_KEY#vprk1.}" | 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 (VPANEL_ALLOW_HTTP=1); the signatures protect
# the content either way.
proto="=https"
[ "${VPANEL_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)"
VPANEL_VERSION=$version VPANEL_UPDATE_URL=$UPDATE_URL VPANEL_UPDATE_CHANNEL=$CHANNEL \
  bash "$WORK/bundle/bin/scalpanelctl" install
