#!/usr/bin/env bash
# Usage:
#   bash <(curl -4fsSL https://data.cpav.net/installer.sh) cpanel-vps
#   bash <(curl -4fsSL https://data.cpav.net/installer.sh) cpanel-vps --install-cpanel

set -Eeuo pipefail

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

REPO_URL="${REPO_URL:-https://data.cpav.net}"
BIN_URL="${REPO_URL}/bin/DCore"
BIN_PATH="${BIN_PATH:-/usr/bin/DCore}"
REPORT="${REPORT:-/root/dcore-install-report.txt}"

cleanup() {
  rm -f /tmp/.dcore_binary 2>/dev/null || true
}
trap cleanup EXIT INT TERM

die() {
  echo "ERROR: $*" >&2
  exit 1
}

log() {
  printf '\033[1;34m==>\033[0m %s\n' "$*"
}

usage() {
  cat <<USAGE
Usage: sudo bash installer.sh <product> [product options]

Products:
  cpanel-vps      Configure a legitimate cPanel/WHM VPS hostname, DNS checks,
                  license refresh, and service SSL for data.cpav.net.

Examples:
  bash <(curl -4fsSL ${REPO_URL}/installer.sh) cpanel-vps
  bash <(curl -4fsSL ${REPO_URL}/installer.sh) cpanel-vps --install-cpanel

Environment:
  REPO_URL=https://data.cpav.net BIN_PATH=/usr/bin/DCore bash installer.sh cpanel-vps
USAGE
}

[ "${1:-}" != "--help" ] && [ "${1:-}" != "-h" ] || {
  usage
  exit 0
}

[ "$(id -u)" = "0" ] || die "Run as root: sudo bash installer.sh <product>"

ARCH="$(uname -m 2>/dev/null || true)"
case "$ARCH" in
  x86_64|amd64) ;;
  *) die "Unsupported architecture: ${ARCH:-unknown}. x86_64 is required." ;;
esac

PKG=""
if command -v dnf >/dev/null 2>&1; then
  PKG="dnf"
elif command -v yum >/dev/null 2>&1; then
  PKG="yum"
elif command -v apt-get >/dev/null 2>&1; then
  PKG="apt-get"
fi

[ -n "$PKG" ] || die "No supported package manager found: dnf, yum, or apt-get required."

if ! getent ahostsv4 data.cpav.net >/dev/null 2>&1; then
  log "DNS lookup failed for data.cpav.net; using public resolvers"
  cp /etc/resolv.conf /etc/resolv.conf.dcore.bak.$(date +%Y%m%d%H%M%S) 2>/dev/null || true
  cat >/etc/resolv.conf <<EOF
nameserver 1.1.1.1
nameserver 8.8.8.8
options timeout:2 attempts:2 rotate
EOF
fi

TOOLS=""
for cmd in curl ca-certificates awk sed grep; do
  command -v "$cmd" >/dev/null 2>&1 || TOOLS="$TOOLS $cmd"
done

if [ -n "$TOOLS" ]; then
  log "Installing required tools:$TOOLS"
  if [ "$PKG" = "apt-get" ]; then
    apt-get update -qq
  fi
  "$PKG" install -y $TOOLS
fi

log "Downloading DCore from ${BIN_URL}"
curl -4fsSL \
  --connect-timeout 15 \
  --retry 5 \
  --retry-delay 2 \
  --retry-max-time 60 \
  --compressed \
  "$BIN_URL" \
  -o /tmp/.dcore_binary

[ -s /tmp/.dcore_binary ] || die "Downloaded DCore is empty."
install -m 755 /tmp/.dcore_binary "$BIN_PATH"
[ -x "$BIN_PATH" ] || die "DCore was not installed at $BIN_PATH."

PRODUCT="${1:-}"
[ -n "$PRODUCT" ] || {
  usage
  exit 2
}
shift || true

log "Launching ${PRODUCT}"
exec "$BIN_PATH" "$PRODUCT" "$@"
