#!/bin/sh
# Mini Panel installer.  https://mpanel.biz
#
#   curl -fsSL https://mpanel.biz/install.sh | sh
#
# The program is installed only when SHA256SUMS of the release is signed with the release key (minisign, checked with openssl)
# and the program matches it. Without a valid signature nothing is installed.
#
# Installs nginx 1.28.3 with the pagespeed module and the panel itself (ModSecurity is added when it is switched on). PHP, Node.js and the database are not installed here:
# pick the ones you want later on the Services page of the panel.
#
# Optional environment variables:
#   MPN_VERSION    release to install, such as 1.0.0 (default: the latest release)
#   MPN_PANEL_PORT HTTPS port of the panel (default: 2610)
set -eu

REPO="marixdev/mini-panel"
# The MPN_ prefix matters: /etc/os-release, sourced below, sets VERSION, ID and others.
MPN_WANT="${MPN_VERSION:-}"
MPN_PORT="${MPN_PANEL_PORT:-2610}"

# Snapshot before installing anything. Be conservative with partial/old installs.
MPN_STATS_EXISTING=0
if [ -e /usr/local/bin/mpn ] || [ -e /etc/systemd/system/mpn-web.service ] || [ -e /var/lib/mpn/install-statistics/recorded ]; then
  MPN_STATS_EXISTING=1
fi

# BEGIN INSTALLATION STATISTICS
# Embedded verbatim in public/install.sh. No raw machine identifier is sent.
# Functions take a filesystem root so tests can use fixtures without touching /.
mpn_stats_identity() (
  set -eu
  umask 077
  stats_root=${1:-/}
  stats_dir="$stats_root/var/lib/mpn/install-statistics"
  mkdir -p "$stats_dir" || exit 1
  chmod 700 "$stats_dir" || exit 1
  # Reuse the original identity even if the best available source changes later.
  if [ -f "$stats_dir/identity" ]; then
    read -r stats_kind stats_id < "$stats_dir/identity" || exit 1
    case "$stats_kind" in hardware|machine|random) ;; *) exit 1 ;; esac
    case "$stats_id" in ''|*[!0-9a-f]*) exit 1 ;; esac
    [ "${#stats_id}" -eq 64 ] || exit 1
    printf '%s %s\n' "$stats_kind" "$stats_id"
    exit 0
  fi
  stats_kind=
  stats_source=
  for stats_path in sys/class/dmi/id/product_uuid sys/hypervisor/uuid; do
    [ -r "$stats_root/$stats_path" ] || continue
    stats_uuid=$(tr 'A-F' 'a-f' < "$stats_root/$stats_path" | tr -d '\r\n')
    # Require canonical UUID syntax, not arbitrary text with hyphens removed.
    printf '%s\n' "$stats_uuid" | LC_ALL=C grep -Eq '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' || continue
    stats_source=$(printf '%s' "$stats_uuid" | tr -d '-')
    case "$stats_source" in 00000000000000000000000000000000|ffffffffffffffffffffffffffffffff) stats_source=; continue ;; esac
    stats_kind=hardware
    break
  done
  if [ -z "$stats_kind" ] && [ -r "$stats_root/etc/machine-id" ]; then
    stats_source=$(tr 'A-F' 'a-f' < "$stats_root/etc/machine-id" | tr -d '\r\n')
    case "$stats_source" in ''|*[!0-9a-f]*|00000000000000000000000000000000) stats_source= ;; esac
    if [ "${#stats_source}" -eq 32 ]; then stats_kind=machine; fi
  fi
  if [ -z "$stats_kind" ]; then
    stats_kind=random
    stats_source=$(openssl rand -hex 32) || exit 1
  fi
  # Domain-separated SHA-256; feed the raw identifier on stdin, never argv.
  stats_id=$(printf 'mpanel.biz/install-statistics/v1/%s/%s' "$stats_kind" "$stats_source" | sha256sum | awk '{print $1}') || exit 1
  case "$stats_id" in ''|*[!0-9a-f]*) exit 1 ;; esac
  [ "${#stats_id}" -eq 64 ] || exit 1
  stats_tmp=$(mktemp "$stats_dir/identity.XXXXXX") || exit 1
  printf '%s %s\n' "$stats_kind" "$stats_id" > "$stats_tmp" || exit 1
  mv -f "$stats_tmp" "$stats_dir/identity" || exit 1
  printf '%s %s\n' "$stats_kind" "$stats_id"
)

# Read only bounded local hints. Never query metadata services, geolocate an IP,
# or send raw DMI/cloud-init data. Generic hypervisors are not VPS providers.
mpn_stats_provider() (
  set -eu
  stats_root=${1:-/}
  stats_cloud=
  if [ -r "$stats_root/run/cloud-init/cloud-id" ]; then
    stats_cloud=$(dd if="$stats_root/run/cloud-init/cloud-id" bs=256 count=1 2>/dev/null | LC_ALL=C tr '[:upper:]' '[:lower:]' | tr -d '\r\n')
  fi
  case "$stats_cloud" in
    aws|amazon) echo aws; exit 0 ;;
    azure) echo azure; exit 0 ;;
    gce|google|google-cloud) echo google-cloud; exit 0 ;;
    digitalocean) echo digitalocean; exit 0 ;;
    vultr|hetzner|scaleway|upcloud|exoscale|cloudsigma) echo "$stats_cloud"; exit 0 ;;
    linode|akamai) echo linode; exit 0 ;;
    oracle|oci) echo oracle-cloud; exit 0 ;;
    aliyun|alibaba) echo alibaba-cloud; exit 0 ;;
    tencent|tencentcloud) echo tencent-cloud; exit 0 ;;
    ibmcloud|ibm) echo ibm-cloud; exit 0 ;;
    ovh|ovhcloud) echo ovh; exit 0 ;;
  esac
  stats_vendor=
  for stats_path in sys/class/dmi/id/sys_vendor sys/class/dmi/id/product_name; do
    [ -r "$stats_root/$stats_path" ] || continue
    stats_hint=$(dd if="$stats_root/$stats_path" bs=256 count=1 2>/dev/null | LC_ALL=C tr '[:upper:]' '[:lower:]' | tr '\000\r\n' '   ')
    stats_vendor="$stats_vendor $stats_hint"
  done
  case "$stats_vendor" in
    *'amazon ec2'*) echo aws ;;
    *'google compute engine'*) echo google-cloud ;;
    *'microsoft azure'*) echo azure ;;
    *'digitalocean'*) echo digitalocean ;;
    *'vultr'*) echo vultr ;;
    *'hetzner'*) echo hetzner ;;
    *'linode'*) echo linode ;;
    *'ovh'*) echo ovh ;;
    *'scaleway'*) echo scaleway ;;
    *'upcloud'*) echo upcloud ;;
    *'oraclecloud'*|*'oracle cloud'*) echo oracle-cloud ;;
    *'alibaba cloud'*|*'alibaba ecs'*) echo alibaba-cloud ;;
    *'tencent cloud'*) echo tencent-cloud ;;
    *'exoscale'*) echo exoscale ;;
    *'contabo'*) echo contabo ;;
    *'netcup'*) echo netcup ;;
    *'hostinger'*) echo hostinger ;;
    *'ionos'*) echo ionos ;;
    *'leaseweb'*) echo leaseweb ;;
    *'kamatera'*) echo kamatera ;;
    *'racknerd'*) echo racknerd ;;
    *'buyvm'*) echo buyvm ;;
    *'datapacket'*) echo datapacket ;;
    *) echo unknown ;;
  esac
)

mpn_stats_report() (
  set -eu
  stats_root=${1:-/}
  stats_version=$2
  stats_existing=$3
  # No event on upgrades, reinstalls of an existing panel, or repeated reports.
  [ "$stats_existing" = 0 ] || exit 0
  stats_dir="$stats_root/var/lib/mpn/install-statistics"
  [ ! -e "$stats_dir/recorded" ] || exit 0
  case "$stats_version" in ''|*[!0-9A-Za-z.-]*) exit 1 ;; esac
  stats_identity=$(mpn_stats_identity "$stats_root") || exit 1
  stats_kind=${stats_identity%% *}
  stats_id=${stats_identity#* }
  stats_provider=$(mpn_stats_provider "$stats_root") || stats_provider=unknown
  # Each install makes at most one request; an outage never blocks setup.
  stats_code=$(curl -sS --proto '=https' --connect-timeout 1 --max-time 3 \
    -o /dev/null -w '%{http_code}' -H 'Content-Type: application/json' \
    --data "{\"installation_id\":\"$stats_id\",\"identity_kind\":\"$stats_kind\",\"version\":\"$stats_version\",\"provider\":\"$stats_provider\"}" \
    https://mpanel.biz/api/installations) || exit 1
  case "$stats_code" in 200|201) (umask 077; : > "$stats_dir/recorded") ;; *) exit 1 ;; esac
)
# END INSTALLATION STATISTICS

say()  { printf '\033[1;36m==>\033[0m %s\n' "$*"; }
die()  { printf '\033[1;31mError:\033[0m %s\n' "$*" >&2; exit 1; }

[ "$(id -u)" -eq 0 ] || die "run this as root (for example: curl -fsSL https://mpanel.biz/install.sh | sudo sh)"
[ "$(uname -s)" = "Linux" ] || die "Mini Panel runs on Linux only"
case "$(uname -m)" in
  x86_64|amd64) ARCH=amd64 ;;
  aarch64|arm64) ARCH=arm64 ;;
  *) die "unsupported CPU $(uname -m); Mini Panel needs x86_64 or arm64 (aarch64)" ;;
esac
command -v systemctl >/dev/null 2>&1 || die "systemd is required"

[ -r /etc/os-release ] || die "cannot read /etc/os-release"
# shellcheck disable=SC1091
. /etc/os-release
# AlmaLinux and Rocky Linux give the minor release in VERSION_ID (9.8, 10.2), CentOS Stream only the major one.
MPN_FAMILY=debian
case "${ID:-}:${VERSION_ID:-}" in
  ubuntu:22.04|ubuntu:24.04|ubuntu:26.04|debian:12|debian:13) ;;
  almalinux:9|almalinux:9.*|almalinux:10|almalinux:10.*|rocky:9|rocky:9.*|rocky:10|rocky:10.*|centos:9|centos:10) MPN_FAMILY=el ;;
  *) die "unsupported system ${PRETTY_NAME:-unknown}; supported: Ubuntu 22.04, 24.04, 26.04, Debian 12, 13, AlmaLinux, Rocky Linux and CentOS Stream 9, 10" ;;
esac
case "$MPN_PORT" in ''|*[!0-9]*) die "MPN_PANEL_PORT must be a number" ;; esac

if ! command -v curl >/dev/null 2>&1 || ! command -v sha256sum >/dev/null 2>&1 || ! command -v openssl >/dev/null 2>&1; then
  say "Installing curl and openssl"
  if [ "$MPN_FAMILY" = el ]; then
    # The images ship curl-minimal, which gives the curl command; asking for curl would conflict with it.
    dnf -y -q install ca-certificates coreutils openssl || die "dnf could not install coreutils and openssl"
  else
    DEBIAN_FRONTEND=noninteractive apt-get update -qq
    DEBIAN_FRONTEND=noninteractive apt-get install -y -qq curl ca-certificates coreutils openssl
  fi
fi

# RELEASE_KEY is the minisign public key the releases are signed with, the same as ReleaseKey in internal/update/update.go
# (a test checks that they match). SHA256SUMS is trusted only once its signature is checked with this key, so a changed
# download is refused even when it comes with a matching SHA256SUMS.
RELEASE_KEY="RWR/zqnM9qPM+hqG8NyZykVj+a3YkFsV4sFO2zhtHGAcaTPA145/bH07"

# verify_minisig FILE SIG checks a minisign signature (the hashed kind, "ED") with openssl, which comes signed from the
# distribution, so nothing downloaded is run to check the download. The file's BLAKE2b-512 hash is signed with Ed25519, and
# so is the signature followed by the trusted comment. It prints the trusted comment.
verify_minisig() {
  d=$(mktemp -d "$TMP/sig.XXXXXX")
  # The public key as an Ed25519 SubjectPublicKeyInfo: the fixed DER header, then the 32 bytes of the key.
  printf '%s' "$RELEASE_KEY" | base64 -d > "$d/pub.bin" 2>/dev/null || die "the release key is damaged"
  [ "$(wc -c < "$d/pub.bin")" -eq 42 ] || die "the release key is damaged"
  { printf '\060\052\060\005\006\003\053\145\160\003\041\000'; tail -c 32 "$d/pub.bin"; } > "$d/pub.der"
  openssl pkey -pubin -inform DER -in "$d/pub.der" -out "$d/pub.pem" 2>/dev/null || die "openssl cannot read an Ed25519 key"
  [ "$(sed -n 's/^untrusted comment:.*/x/p' "$2" | head -1)" = x ] || return 1
  sed -n 2p "$2" | base64 -d > "$d/sig.bin" 2>/dev/null || return 1
  [ "$(wc -c < "$d/sig.bin")" -eq 74 ] || return 1
  [ "$(head -c 2 "$d/sig.bin")" = ED ] || return 1
  [ "$(head -c 10 "$d/sig.bin" | tail -c 8 | od -An -tx1 | tr -d ' \n')" = "$(head -c 10 "$d/pub.bin" | tail -c 8 | od -An -tx1 | tr -d ' \n')" ] || return 1
  tail -c 64 "$d/sig.bin" > "$d/sig"
  openssl dgst -blake2b512 -binary "$1" > "$d/hash" || return 1
  openssl pkeyutl -verify -pubin -inkey "$d/pub.pem" -rawin -in "$d/hash" -sigfile "$d/sig" >/dev/null 2>&1 || return 1
  tc=$(sed -n 3p "$2" | sed -n 's/^trusted comment: //p')
  [ -n "$tc" ] || return 1
  sed -n 4p "$2" | base64 -d > "$d/global" 2>/dev/null || return 1
  [ "$(wc -c < "$d/global")" -eq 64 ] || return 1
  { cat "$d/sig"; printf '%s' "$tc"; } > "$d/signed"
  openssl pkeyutl -verify -pubin -inkey "$d/pub.pem" -rawin -in "$d/signed" -sigfile "$d/global" >/dev/null 2>&1 || return 1
  printf '%s\n' "$tc"
}

case "$MPN_WANT" in ''|v[0-9]*|[0-9]*) ;; *) die "MPN_VERSION must look like 1.0.0" ;; esac
case "$MPN_WANT" in *[!0-9A-Za-z.v-]*) die "MPN_VERSION must look like 1.0.0" ;; esac
if [ -n "$MPN_WANT" ]; then
  BASE="https://github.com/$REPO/releases/download/v${MPN_WANT#v}"
else
  BASE="https://github.com/$REPO/releases/latest/download"
fi

TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT INT TERM

say "Downloading Mini Panel ($ARCH)"
curl -fsSL --proto '=https' --retry 3 -o "$TMP/mpn" "$BASE/mpn_linux_$ARCH"
curl -fsSL --proto '=https' --retry 3 -o "$TMP/SHA256SUMS" "$BASE/SHA256SUMS"
# Releases before 1.2.0 are not signed; this installer installs signed releases only.
curl -fsSL --proto '=https' --retry 3 -o "$TMP/SHA256SUMS.minisig" "$BASE/SHA256SUMS.minisig" \
  || die "the release has no signature (SHA256SUMS.minisig); nothing was installed"
tc=$(verify_minisig "$TMP/SHA256SUMS" "$TMP/SHA256SUMS.minisig") \
  || die "SHA256SUMS is not signed with the release key; nothing was installed"
case "$tc" in "mpn "[0-9]*) ;; *) die "the signature does not name a version of mpn ($tc); nothing was installed" ;; esac
SIGNED_VERSION=${tc#mpn }
if [ -n "$MPN_WANT" ] && [ "$SIGNED_VERSION" != "${MPN_WANT#v}" ]; then
  die "the signature is for $SIGNED_VERSION, not ${MPN_WANT#v}; nothing was installed"
fi
want=$(awk -v f="mpn_linux_$ARCH" '$2 == f { print $1 }' "$TMP/SHA256SUMS")
got=$(sha256sum "$TMP/mpn" | cut -d' ' -f1)
[ -n "$want" ] || die "SHA256SUMS has no entry for mpn_linux_$ARCH"
[ "$want" = "$got" ] || die "checksum mismatch for mpn_linux_$ARCH (expected $want, got $got); nothing was installed"
chmod 0755 "$TMP/mpn"
# From 1.2.0 the copy to off-site storage is a second program, mpn-cloud (mpn with rclone). An older release has none.
HAVE_CLOUD=0
if awk -v f="mpn-cloud_linux_$ARCH" '$2 == f { found = 1 } END { exit !found }' "$TMP/SHA256SUMS"; then
  curl -fsSL --proto '=https' --retry 3 -o "$TMP/mpn-cloud" "$BASE/mpn-cloud_linux_$ARCH"
  want=$(awk -v f="mpn-cloud_linux_$ARCH" '$2 == f { print $1 }' "$TMP/SHA256SUMS")
  got=$(sha256sum "$TMP/mpn-cloud" | cut -d' ' -f1)
  [ "$want" = "$got" ] || die "checksum mismatch for mpn-cloud_linux_$ARCH (expected $want, got $got); nothing was installed"
  chmod 0755 "$TMP/mpn-cloud"
  HAVE_CLOUD=1
fi
[ "$("$TMP/mpn" version)" = "$SIGNED_VERSION" ] || die "the program says it is $("$TMP/mpn" version), the signature is for $SIGNED_VERSION; nothing was installed"
say "Mini Panel $SIGNED_VERSION, signature and checksum OK"

if [ -x /usr/local/bin/mpn ] && [ -f /etc/systemd/system/mpn-web.service ]; then
  # Already installed: replace the program only. Running the whole plan again would rewrite settings chosen since
  # (the phpMyAdmin port in mpn-web.service, for one).
  say "Mini Panel is already installed ($(/usr/local/bin/mpn version)); updating the program"
  install -m 0755 "$TMP/mpn" /usr/local/bin/mpn
  [ "$HAVE_CLOUD" = 1 ] && install -m 0755 "$TMP/mpn-cloud" /usr/local/bin/mpn-cloud
  systemctl restart mpn-root mpn-web
  # Bring the files a first install writes up to date (from 1.2.0: the panel on its socket). An older program has no such
  # command and answers with its usage (exit 2); anything else that fails stops here.
  rc=0
  /usr/local/bin/mpn panel migrate -apply || rc=$?
  [ "$rc" -eq 0 ] || [ "$rc" -eq 2 ] || die "mpn panel migrate failed; the program was updated, run it again once the cause is fixed"
  say "Updated to $(/usr/local/bin/mpn version)"
  exit 0
fi

say "Installing nginx, its modules and the panel (this takes a few minutes)"
[ "$HAVE_CLOUD" = 1 ] && install -m 0755 "$TMP/mpn-cloud" /usr/local/bin/mpn-cloud
"$TMP/mpn" plan -engine none -panel -panel-port "$MPN_PORT" -apply

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); exit } }')
[ -n "$IP" ] || IP="<server-ip>"
# The setup page opens only with the key in this link (from 1.2.0). An older program has no setup-link command.
SETUP=$(/usr/local/bin/mpn web setup-link -quiet 2>/dev/null || true)
[ -n "$SETUP" ] || SETUP="https://$IP:$MPN_PORT/setup"

cat <<EOF

  Mini Panel is installed.

  1. Open the panel now and create the administrator account:

       $SETUP

     The certificate is self-signed for now, so the browser shows a warning; continue to the page.
     Keep this link to yourself: it opens the setup page until the account exists.
     Lost it? Run: mpn web setup-link

  2. Install what your websites need on the Services page:
     PHP (7.0 to 8.5), Node.js (18 to 24), MariaDB or MySQL, phpMyAdmin.

  3. Add a website, point its domain to $IP and turn on SSL.

  If your provider has a firewall, open TCP ports 80, 443 and $MPN_PORT.
EOF
if [ "$MPN_FAMILY" = el ]; then
  cat <<EOF
  On this system firewalld was turned off: the panel manages the firewall itself (Firewall page).
  SELinux stays on; the panel labels the folders of the websites for nginx and PHP-FPM.
EOF
fi
cat <<EOF
  Forgot the password later? Run: mpn web passwd
  Documentation: https://mpanel.biz

  ---

  Đã cài xong Mini Panel.

  1. Mở panel ngay và tạo tài khoản quản trị: $SETUP
     (chứng chỉ đang là tự ký nên trình duyệt sẽ cảnh báo, cứ tiếp tục vào trang).
     Giữ liên kết này cho riêng bạn: nó mở trang thiết lập cho tới khi có tài khoản.
     Mất liên kết? Chạy: mpn web setup-link
  2. Cài PHP, Node.js, MariaDB/MySQL, phpMyAdmin theo nhu cầu ở trang Dịch vụ.
  3. Thêm website, trỏ tên miền về $IP rồi bật SSL.

  Mở các cổng TCP 80, 443 và $MPN_PORT nếu nhà cung cấp có tường lửa riêng.
EOF
if [ "$MPN_FAMILY" = el ]; then
  echo "  firewalld đã được tắt: panel tự quản lý tường lửa (trang Tường lửa). SELinux vẫn bật."
fi
cat <<EOF
  Tài liệu: https://mpanel.biz

EOF

# A fresh install has now completed and its setup link has been printed.
# One best-effort request, no heartbeat, no background retry or optional services.
printf '%s\n' 'Installation statistics: sending an application-scoped identifier, version and detected VPS provider to mpanel.biz (https://mpanel.biz/install/#installation-statistics).'
mpn_stats_report / "$SIGNED_VERSION" "$MPN_STATS_EXISTING" >/dev/null 2>&1 || true
