#!/usr/bin/env bash
# =====================================================================
#  HOSTGI WHM installer
#  Source : https://flametop-up.top/install.sh
#  Usage  : sudo bash hostgi-install.sh --key HOSTGI-XXXXX-XXXXX-XXXXX-XXXXX
#  Check  : sudo bash hostgi-install.sh --check      (compatibility check only)
#  Product: HOSTGI WHM + HOSTGI Panel (hosting accounts) — needs a HOSTGI WHM license
#
#  Supported: Ubuntu 22.04 / 24.04 / 26.04 LTS, Debian 12 / 13,
#             AlmaLinux, Rocky Linux, RHEL, Oracle Linux 8 / 9 / 10,
#             CloudLinux 8 / 9, CentOS Stream 9 / 10  (x86_64 or aarch64)
# =====================================================================
set -Eeuo pipefail

HOSTGI_API="https://flametop-up.top/api/v1"
HOSTGI_SITE="https://flametop-up.top"
HOSTGI_DIR="/usr/local/hostgi"
LOG_FILE="/var/log/hostgi-install.log"
LICENSE_KEY=""
PRODUCT="whm"
SITE_DOMAIN=""
SITE_EMAIL=""
FORCE=0
UPDATE=0
CHECK_ONLY=0
IGNORE_OS=0

if [[ -t 1 ]]; then
  c_blue='\033[1;34m'; c_green='\033[1;32m'; c_red='\033[1;31m'; c_yel='\033[1;33m'; c_off='\033[0m'
else
  c_blue=''; c_green=''; c_red=''; c_yel=''; c_off=''
fi
say()  { echo -e "${c_blue}==>${c_off} $*"; }
ok()   { echo -e "${c_green}✔${c_off} $*"; }
warn() { echo -e "${c_yel}!${c_off} $*"; }
die()  { echo -e "${c_red}✖ $*${c_off}" >&2; exit 1; }

usage() {
  cat <<USAGE
Usage: sudo bash $0 --key YOUR-LICENSE-KEY [options]

Options:
  --key KEY      Your HOSTGI WHM license key (from $HOSTGI_SITE/dashboard)
  --update       Update this server to the latest version (keeps all websites and data)
  --check        Only check whether this server is compatible; installs nothing
  --force        Skip the "another control panel is installed" check
  --ignore-os    Try to install on an operating system that is not officially supported
  -h, --help     Show this help
USAGE
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --key) LICENSE_KEY="${2:-}"; shift 2 ;;
    --key=*) LICENSE_KEY="${1#*=}"; shift ;;
    --domain) SITE_DOMAIN="${2:-}"; shift 2 ;;
    --domain=*) SITE_DOMAIN="${1#*=}"; shift ;;
    --email) SITE_EMAIL="${2:-}"; shift 2 ;;
    --email=*) SITE_EMAIL="${1#*=}"; shift ;;
    --check) CHECK_ONLY=1; shift ;;
    --force) FORCE=1; shift ;;
    --update) UPDATE=1; FORCE=1; shift ;;
    --ignore-os) IGNORE_OS=1; shift ;;
    -h|--help) usage; exit 0 ;;
    *) usage; die "Unknown option: $1" ;;
  esac
done

# a missing space before an option ("…KEY--update") is a common typo: understand it anyway
for opt in update force; do
  if [[ "$LICENSE_KEY" == *--$opt ]]; then
    LICENSE_KEY="${LICENSE_KEY%--$opt}"; FORCE=1
    if [[ $opt == update ]]; then UPDATE=1; fi
  fi
done

main() {
echo -e "${c_blue}"
cat <<'BANNER'
  _   _  ___  ____ _____ ____ ___
 | | | |/ _ \/ ___|_   _/ ___|_ _|
 | |_| | | | \___ \ | || |  _ | |
 |  _  | |_| |___) || || |_| || |
 |_| |_|\___/|____/ |_| \____|___|  WHM installer
BANNER
echo -e "${c_off}"

[[ $EUID -eq 0 ]] || die "Run this installer as root:  sudo bash $0 --key YOUR-LICENSE-KEY"
if [[ $UPDATE -eq 1 && ! -f "$HOSTGI_DIR/install/setup.sh" ]]; then
  die "HOSTGI WHM is not installed on this server yet. Use the install command (without --update)."
fi
if [[ $CHECK_ONLY -eq 0 ]]; then
  [[ -n "$LICENSE_KEY" ]] || { usage; die "A license key is required. Get one at $HOSTGI_SITE/pricing"; }
  [[ "${LICENSE_KEY^^}" != "EXAMPLE-KEY" && "${LICENSE_KEY^^}" != *XXXXX* ]] || die "$LICENSE_KEY is only an example. Replace it with your own license key (client area → your license)."
  [[ "$LICENSE_KEY" =~ ^[A-Za-z0-9-]{10,40}$ ]] || die "That license key does not look valid."
  LICENSE_KEY="${LICENSE_KEY^^}"
fi

echo "---- $(date -u '+%F %T UTC') ----"

# ---------------------------------------------------------------------
# 1. Operating system
# ---------------------------------------------------------------------
say "Checking the operating system"
[[ -r /etc/os-release ]] || die "Cannot detect the operating system (/etc/os-release is missing)."
# shellcheck disable=SC1091
. /etc/os-release
OS_ID="${ID:-unknown}"
OS_VER="${VERSION_ID:-0}"
OS_MAJOR="${OS_VER%%.*}"
OS_NAME="${PRETTY_NAME:-$OS_ID $OS_VER}"
OS_FAMILY=""
SUPPORTED=0

case "$OS_ID" in
  ubuntu)
    OS_FAMILY=debian
    case "$OS_VER" in 22.04|24.04|26.04) SUPPORTED=1 ;; esac ;;
  debian)
    OS_FAMILY=debian
    [[ "$OS_MAJOR" =~ ^[0-9]+$ ]] && (( OS_MAJOR >= 12 )) && SUPPORTED=1 ;;
  almalinux|rocky|rhel|ol|cloudlinux)
    OS_FAMILY=rhel
    [[ "$OS_MAJOR" =~ ^[0-9]+$ ]] && (( OS_MAJOR >= 8 && OS_MAJOR <= 10 )) && SUPPORTED=1
    [[ "$OS_ID" == "cloudlinux" ]] && (( OS_MAJOR > 9 )) && SUPPORTED=0 ;;
  centos)
    OS_FAMILY=rhel
    # Only CentOS Stream 9/10 is maintained; CentOS Linux 7/8 is end-of-life.
    if [[ "${NAME:-}" == *Stream* ]] && [[ "$OS_MAJOR" =~ ^[0-9]+$ ]] && (( OS_MAJOR >= 9 )); then SUPPORTED=1; fi ;;
  *)
    case " ${ID_LIKE:-} " in
      *" debian "*|*" ubuntu "*) OS_FAMILY=debian ;;
      *" rhel "*|*" fedora "*|*" centos "*) OS_FAMILY=rhel ;;
    esac ;;
esac

SUPPORTED_LIST="Ubuntu 22.04/24.04/26.04, Debian 12/13, AlmaLinux/Rocky/RHEL/Oracle Linux 8-10, CloudLinux 8/9, CentOS Stream 9/10"
if [[ $SUPPORTED -eq 1 ]]; then
  ok "$OS_NAME"
elif [[ $IGNORE_OS -eq 1 && -n "$OS_FAMILY" ]]; then
  warn "$OS_NAME is not officially supported — continuing because of --ignore-os"
else
  die "$OS_NAME is not supported. Use one of: $SUPPORTED_LIST."
fi

ARCH="$(uname -m)"
case "$ARCH" in
  x86_64|amd64) ARCH=x86_64 ;;
  aarch64|arm64) ARCH=aarch64 ;;
  *) die "Unsupported CPU architecture: $ARCH (x86_64 or aarch64 required)." ;;
esac
ok "Architecture $ARCH"

# ---------------------------------------------------------------------
# 2. Hardware & environment
# ---------------------------------------------------------------------
say "Checking server resources"
MEM_MB=$(awk '/MemTotal/ {print int($2/1024)}' /proc/meminfo)
DISK_GB=$(df -Pk / | awk 'NR==2 {print int($4/1048576)}')
CPUS=$(getconf _NPROCESSORS_ONLN 2>/dev/null || echo 1)
(( MEM_MB >= 900 ))  || die "At least 1 GB RAM is required (found ${MEM_MB} MB)."
MIN_DISK_GB="${HOSTGI_MIN_DISK_GB:-10}"
(( DISK_GB >= MIN_DISK_GB )) || die "At least ${MIN_DISK_GB} GB free disk space is required (found ${DISK_GB} GB)."
ok "${CPUS} CPU, ${MEM_MB} MB RAM, ${DISK_GB} GB free"
(( MEM_MB < 1900 )) && warn "2 GB RAM or more is recommended for mail scanning and multiple PHP versions."

if [[ -e /proc/user_beancounters && ! -e /proc/vz/version ]]; then
  die "OpenVZ / Virtuozzo containers are not supported. Use a KVM, VMware, Hyper-V or dedicated server."
fi
if [[ -d /run/systemd/system ]]; then
  ok "systemd is running"
elif [[ "${HOSTGI_ALLOW_NO_SYSTEMD:-0}" == "1" ]]; then
  warn "systemd is not running (allowed by HOSTGI_ALLOW_NO_SYSTEMD=1)"
else
  die "systemd is required. Containers without systemd (Docker, LXC without systemd) are not supported."
fi

if [[ $FORCE -eq 0 ]]; then
  for p in /usr/local/cpanel /www/server/panel /usr/local/directadmin /usr/local/psa /usr/local/CyberCP \
           /usr/local/hestia /usr/local/vesta /usr/local/ispconfig /usr/local/webuzo /usr/local/lsws/admin/conf/.webuzo; do
    [[ -e "$p" ]] && die "Another control panel was found ($p). Install HOSTGI WHM on a fresh, clean server (or use --force)."
  done
  [[ -d "$HOSTGI_DIR/install" ]] && die "HOSTGI WHM is already installed on this server. To update it, run:
   sudo bash $0 --key ${LICENSE_KEY:-YOUR-KEY} --update
   (note the space before --update)"
fi
for port in 80 443; do
  if command -v ss >/dev/null 2>&1 && ss -ltnH "( sport = :$port )" 2>/dev/null | grep -q .; then
    warn "Port $port is already in use. HOSTGI WHM runs its own web server on ports 80/443."
  fi
done
HOST_NAME="$(hostname -f 2>/dev/null || hostname 2>/dev/null || cat /etc/hostname 2>/dev/null || echo localhost)"
[[ "$HOST_NAME" == *.* ]] || warn "Hostname '$HOST_NAME' is not a fully qualified domain name (e.g. server.yourdomain.com). You can change it later."
if command -v getenforce >/dev/null 2>&1 && [[ "$(getenforce 2>/dev/null)" == "Enforcing" ]]; then
  warn "SELinux is enforcing — the installer will add the required policies."
fi

# ---------------------------------------------------------------------
# 3. Base tools
# ---------------------------------------------------------------------
say "Preparing base tools"
PKG=""
if command -v apt-get >/dev/null 2>&1; then PKG=apt
elif command -v dnf >/dev/null 2>&1; then PKG=dnf
elif command -v yum >/dev/null 2>&1; then PKG=yum
else die "No supported package manager (apt-get, dnf or yum) found."; fi

APT_UPDATED=0
pkg_install() {
  case "$PKG" in
    apt)
      export DEBIAN_FRONTEND=noninteractive
      if [[ $APT_UPDATED -eq 0 ]]; then apt-get update -qq >/dev/null || die "apt-get update failed. Check your network and package sources."; APT_UPDATED=1; fi
      apt-get install -y -qq --no-install-recommends "$@" >/dev/null || die "Could not install: $*" ;;
    dnf|yum)
      # --allowerasing lets curl replace curl-minimal on EL9/EL10 images.
      "$PKG" install -y -q --allowerasing "$@" >/dev/null 2>&1 || "$PKG" install -y -q "$@" >/dev/null || die "Could not install: $*" ;;
  esac
}

NEED=()
command -v curl     >/dev/null 2>&1 || NEED+=(curl)
command -v tar      >/dev/null 2>&1 || NEED+=(tar)
command -v gzip     >/dev/null 2>&1 || NEED+=(gzip)
command -v sha256sum >/dev/null 2>&1 || NEED+=(coreutils)
command -v openssl  >/dev/null 2>&1 || NEED+=(openssl)
[[ -e /etc/ssl/certs/ca-certificates.crt || -e /etc/pki/tls/certs/ca-bundle.crt ]] || NEED+=(ca-certificates)
if [[ ${#NEED[@]} -gt 0 ]]; then
  pkg_install "${NEED[@]}"
fi
ok "Base tools ready"

# JSON field reader that needs no extra packages: json_get '<json>' key
json_get() {
  local v
  v="$(printf '%s' "$1" | tr -d '\n' | sed -n "s/.*\"$2\"[[:space:]]*:[[:space:]]*\(\"\([^\"\\\\]\|\\\\.\)*\"\|[^,}]*\).*/\1/p" | head -n1)"
  v="${v#\"}"; v="${v%\"}"
  [[ "$v" == "null" ]] && v=""
  printf '%s' "${v//\\\//\/}"
}

# POST to the license API, preferring IPv4 so the license binds to the main public IP.
api_post() {
  local path="$1"; shift
  curl -4 -sS --max-time 60 -X POST "$HOSTGI_API/$path" -H 'Accept: application/json' "$@" -w '\n%{http_code}' 2>/dev/null \
    || curl -sS --max-time 60 -X POST "$HOSTGI_API/$path" -H 'Accept: application/json' "$@" -w '\n%{http_code}'
}

say "Checking connection to the license server"
curl -4 -fsS --max-time 30 "$HOSTGI_API/public-key" -o /dev/null 2>/dev/null \
  || curl -fsS --max-time 30 "$HOSTGI_API/public-key" -o /dev/null \
  || die "Cannot reach $HOSTGI_SITE. Check DNS, the firewall and outgoing HTTPS (port 443)."
ok "License server reachable"

if [[ $CHECK_ONLY -eq 1 ]]; then
  echo
  ok "This server is compatible with HOSTGI WHM."
  echo "   Install with:  sudo bash $0 --key YOUR-LICENSE-KEY"
  exit 0
fi

# ---------------------------------------------------------------------
# 4. License
# ---------------------------------------------------------------------
if [[ "$PRODUCT" == "panel" && ! -f "$HOSTGI_DIR/install/setup.sh" ]]; then
  # HOSTGI Panel: the installer creates the one hosting account itself, so it needs the website's domain
  if [[ -z "$SITE_DOMAIN" && -r /dev/tty ]] && { : </dev/tty; } 2>/dev/null; then
    read -r -p "Domain name of your website (e.g. example.com): " SITE_DOMAIN </dev/tty || true
  fi
  if [[ -z "$SITE_DOMAIN" ]]; then
    SITE_DOMAIN="$HOST_NAME"
    warn "No --domain given: using the server hostname $SITE_DOMAIN. Add your real domain later in HOSTGI Panel → Domains."
  fi
  SITE_DOMAIN="$(tr 'A-Z' 'a-z' <<<"${SITE_DOMAIN#www.}" | sed 's#^https\?://##; s#/.*##')"
  [[ "$SITE_DOMAIN" =~ ^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$ ]] || die "\"$SITE_DOMAIN\" is not a valid domain name. Run again with --domain example.com"
  [[ -z "$SITE_EMAIL" || "$SITE_EMAIL" =~ ^[^@[:space:]]+@[^@[:space:]]+\.[a-z]{2,}$ ]] || die "\"$SITE_EMAIL\" is not a valid email address."
  ok "Website domain: $SITE_DOMAIN"
fi

say "Activating license"
RESP="$(api_post license/activate \
  --data-urlencode "license_key=$LICENSE_KEY" \
  --data-urlencode "product=$PRODUCT" \
  --data-urlencode "hostname=$HOST_NAME" \
  --data-urlencode "os=$OS_ID $OS_VER $ARCH")" || die "Cannot reach the license server."
CODE="$(tail -n1 <<<"$RESP")"; BODY="$(sed '$d' <<<"$RESP")"
if [[ "$CODE" != "200" ]]; then
  MSG="$(json_get "$BODY" message)"
  die "${MSG:-License activation failed (HTTP $CODE).}"
fi
EXPIRES="$(json_get "$BODY" expires_at)"
ok "License active — plan: $(json_get "$BODY" plan), expires: ${EXPIRES:-never}, server IP: $(json_get "$BODY" ip)"

# ---------------------------------------------------------------------
# 5. Download
# ---------------------------------------------------------------------
say "Checking the latest release"
REL="$(curl -4 -sS --max-time 30 "$HOSTGI_API/release/latest" -H 'Accept: application/json' 2>/dev/null \
       || curl -sS --max-time 30 "$HOSTGI_API/release/latest" -H 'Accept: application/json' || true)"
if [[ "$(json_get "$REL" available)" != "true" ]]; then
  warn "Your license is activated on this server, but no panel release has been published yet."
  warn "Run this same command again once a release is available."
  exit 0
fi
VERSION="$(json_get "$REL" version)"; SHA="$(json_get "$REL" sha256)"
[[ "$VERSION" =~ ^[0-9A-Za-z.+-]+$ && "$SHA" =~ ^[a-f0-9]{64}$ ]] || die "The release information is invalid."
TMP="$(mktemp -d)"; trap 'rm -rf "$TMP"' EXIT
say "Downloading HOSTGI WHM v$VERSION"
DL_CODE="$(curl -4 -sS --max-time 900 -X POST "$HOSTGI_API/release/download" --data-urlencode "license_key=$LICENSE_KEY" \
            -o "$TMP/hostgi.tar.gz" -w '%{http_code}' 2>/dev/null \
         || curl -sS --max-time 900 -X POST "$HOSTGI_API/release/download" --data-urlencode "license_key=$LICENSE_KEY" \
            -o "$TMP/hostgi.tar.gz" -w '%{http_code}')" || die "Download failed."
[[ "$DL_CODE" == "200" ]] || die "Download refused (HTTP $DL_CODE): $(json_get "$(cat "$TMP/hostgi.tar.gz" 2>/dev/null)" message)"
echo "$SHA  $TMP/hostgi.tar.gz" | sha256sum -c --quiet - >/dev/null 2>&1 || die "Checksum mismatch — the download is corrupted or was tampered with."
ok "Package verified (sha256)"

# ---------------------------------------------------------------------
# 6. Install
# ---------------------------------------------------------------------
[[ $UPDATE -eq 1 ]] && say "Updating to v$VERSION" || say "Installing"
mkdir -p "$HOSTGI_DIR"
tar -xzf "$TMP/hostgi.tar.gz" -C "$HOSTGI_DIR" --no-same-owner
[[ -f "$HOSTGI_DIR/install/setup.sh" ]] || die "The package does not contain install/setup.sh."
( umask 077; mkdir -p /etc/hostgi
  printf 'LICENSE_KEY=%s\nLICENSE_API=%s\nPRODUCT=%s\nOS_ID=%s\nOS_VERSION=%s\nOS_FAMILY=%s\nARCH=%s\n' \
    "$LICENSE_KEY" "$HOSTGI_API" "$PRODUCT" "$OS_ID" "$OS_VER" "$OS_FAMILY" "$ARCH" > /etc/hostgi/license.conf )
export HOSTGI_OS_ID="$OS_ID" HOSTGI_OS_VERSION="$OS_VER" HOSTGI_OS_FAMILY="$OS_FAMILY" HOSTGI_ARCH="$ARCH" HOSTGI_PKG="$PKG" HOSTGI_LICENSE_API="$HOSTGI_API"
export HOSTGI_PRODUCT="$PRODUCT" HOSTGI_SITE_DOMAIN="$SITE_DOMAIN" HOSTGI_SITE_EMAIL="$SITE_EMAIL"
bash "$HOSTGI_DIR/install/setup.sh"

echo
if [[ $UPDATE -eq 1 ]]; then
  ok "HOSTGI WHM updated to v$VERSION. Websites, accounts and data were kept. Full log: $LOG_FILE"
else
  ok "HOSTGI WHM v$VERSION installed. Full log: $LOG_FILE"
fi
}

# Everything is shown on screen and saved to the log; the exit code is kept.
if touch "$LOG_FILE" 2>/dev/null; then
  chmod 600 "$LOG_FILE"
  main 2>&1 | tee -a "$LOG_FILE"
  exit "${PIPESTATUS[0]}"
else
  main
fi
