#!/bin/bash
# PanelCP: downloads the current release, checks it and starts its installer.
#   wget -O install.sh https://panelcp.host/install.sh && sudo bash install.sh
# Options are environment variables, for example:  sudo WEB=caddy PANEL_HOST=srv1.example.com bash install.sh
# https://panelcp.host/install/ lists them.

main() {
  set -euo pipefail
  local base="${PANELCP_URL:-https://panelcp.host}" version file sum dir
  stop() { echo "PanelCP: $*" >&2; exit 1; }

  [ "$(id -u)" = 0 ] || stop "run this as root, for example with sudo."
  [ -r /etc/os-release ] || stop "cannot tell which system this is."
  . /etc/os-release
  case "${ID:-}:${VERSION_ID:-}" in
    debian:12|debian:13|ubuntu:22.04|ubuntu:24.04|ubuntu:26.04) ;;
    *) stop "${PRETTY_NAME:-this system} is not supported. Use Debian 12, Debian 13, Ubuntu 22.04, Ubuntu 24.04, Ubuntu 26.04." ;;
  esac
  case "$(uname -m)" in x86_64|aarch64) ;; *) stop "only amd64 and arm64 are supported." ;; esac

  get() { if command -v curl >/dev/null; then curl -fsSL --retry 3 -o "$2" "$1"; else wget -q -O "$2" "$1"; fi; }
  dir="$(mktemp -d /root/panelcp-install.XXXXXX)"
  trap "rm -rf -- '$dir'" EXIT
  get "$base/download/latest.txt" "$dir/latest" || stop "cannot reach $base."
  read -r version file sum < "$dir/latest" || stop "no release has been published yet."
  [[ "$version" =~ ^[0-9.]+$ && "$file" =~ ^[a-z0-9.-]+$ && "$sum" =~ ^[0-9a-f]{64}$ ]] || stop "the release list is damaged, try again later."

  echo "Downloading PanelCP $version"
  get "$base/download/$file" "$dir/$file" || stop "the download failed, try again."
  echo "$sum  $dir/$file" | sha256sum -c --quiet - || stop "the archive is damaged, nothing was installed."
  mkdir "$dir/release"
  tar xzf "$dir/$file" -C "$dir/release" --strip-components=1
  cd "$dir/release"
  bash ./install.sh "$@" < /dev/null
}

# The last line starts everything, so a download that was cut off does nothing.
main "$@"