#!/usr/bin/env bash
set -Eeuo pipefail

DOMAIN="${DOMAIN:-data.cpav.net}"
HOST_SHORT="${DOMAIN%%.*}"
REPORT="${REPORT:-/root/missing-${DOMAIN}.txt}"
INSTALL_CPANEL=0
SKIP_SSL=0

while [ "$#" -gt 0 ]; do
  case "$1" in
    --domain)
      DOMAIN="${2:-}"
      HOST_SHORT="${DOMAIN%%.*}"
      REPORT="${REPORT:-/root/missing-${DOMAIN}.txt}"
      shift 2
      ;;
    --install-cpanel)
      INSTALL_CPANEL=1
      shift
      ;;
    --skip-ssl)
      SKIP_SSL=1
      shift
      ;;
    --help|-h)
      echo "Usage: DCore cpanel-vps [--domain data.cpav.net] [--install-cpanel] [--skip-ssl]"
      exit 0
      ;;
    *)
      echo "Unknown option: $1" >&2
      exit 2
      ;;
  esac
done

: > "$REPORT"

log() { printf '\033[1;34m==>\033[0m %s\n' "$*"; }
ok() { printf '\033[1;32mOK\033[0m %s\n' "$*"; }
warn() { printf '\033[1;33mWARN\033[0m %s\n' "$*"; }
missing() { printf -- '- %s\n' "$*" >> "$REPORT"; warn "$*"; }

[ "$(id -u)" = "0" ] || {
  echo "Run as root." >&2
  exit 1
}

if ! printf '%s' "$DOMAIN" | grep -Eq '^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)+$'; then
  echo "Invalid hostname: $DOMAIN" >&2
  exit 1
fi

install_tools() {
  TOOLS=""
  for cmd in curl perl hostnamectl awk sed grep; do
    command -v "$cmd" >/dev/null 2>&1 || TOOLS="$TOOLS $cmd"
  done
  [ -z "$TOOLS" ] && return

  if command -v dnf >/dev/null 2>&1; then
    dnf install -y $TOOLS
  elif command -v yum >/dev/null 2>&1; then
    yum install -y $TOOLS
  elif command -v apt-get >/dev/null 2>&1; then
    apt-get update -qq
    apt-get install -y $TOOLS
  else
    missing "No supported package manager found to install:$TOOLS"
  fi
}

public_ipv4() {
  IP="$(curl -4fsS --max-time 10 https://cpanel.net/myip 2>/dev/null || true)"
  if ! printf '%s' "$IP" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$'; then
    IP="$(curl -4fsS --max-time 10 https://ifconfig.me 2>/dev/null || true)"
  fi
  printf '%s' "$IP"
}

dns_ipv4() {
  if command -v dig >/dev/null 2>&1; then
    dig +short A "$DOMAIN" | tail -n 1
  elif command -v getent >/dev/null 2>&1; then
    getent ahostsv4 "$DOMAIN" | awk 'NR==1 {print $1}'
  elif command -v nslookup >/dev/null 2>&1; then
    nslookup "$DOMAIN" | awk '/^Address: / {print $2}' | tail -n 1
  fi
}

check_server() {
  ARCH="$(uname -m)"
  MEM_MB="$(awk '/MemTotal/ {printf "%d", $2/1024}' /proc/meminfo 2>/dev/null || echo 0)"
  DISK_MB="$(df -Pm /usr/local 2>/dev/null | awk 'NR==2 {print $4}' || echo 0)"

  [ "$ARCH" = "x86_64" ] || missing "Unsupported architecture: $ARCH. x86_64 required."
  [ "$MEM_MB" -ge 2048 ] || missing "RAM too low: ${MEM_MB}MB detected; 2048MB minimum."
  [ "$DISK_MB" -ge 20480 ] || missing "Disk too low under /usr/local: ${DISK_MB}MB available; 20480MB minimum."
}

configure_hostname() {
  SERVER_IP="$(public_ipv4)"
  DNS_IP="$(dns_ipv4 || true)"

  [ -n "$SERVER_IP" ] || missing "Could not detect server public IPv4."
  if [ -z "$DNS_IP" ]; then
    missing "Create DNS A record: $DOMAIN -> ${SERVER_IP:-YOUR_SERVER_IP}"
  elif [ -n "$SERVER_IP" ] && [ "$DNS_IP" != "$SERVER_IP" ]; then
    missing "DNS mismatch: $DOMAIN points to $DNS_IP, expected $SERVER_IP"
  fi

  hostnamectl set-hostname "$DOMAIN"

  if [ -n "${SERVER_IP:-}" ]; then
    cp /etc/hosts /etc/hosts.dcore.bak.$(date +%Y%m%d%H%M%S) 2>/dev/null || true
    sed -i "/[[:space:]]$DOMAIN\([[:space:]]\|$\)/d" /etc/hosts
    printf '%s\t%s %s\n' "$SERVER_IP" "$DOMAIN" "$HOST_SHORT" >> /etc/hosts
  fi

  if [ -x /usr/local/cpanel/bin/set_hostname ]; then
    /usr/local/cpanel/bin/set_hostname "$DOMAIN"
  fi
}

cpanel_work() {
  if [ -x /usr/local/cpanel/cpanel ] || [ -d /usr/local/cpanel ]; then
    /scripts/upcp --force || missing "cPanel update failed: /scripts/upcp --force"
    if [ -x /usr/local/cpanel/cpkeyclt ]; then
      /usr/local/cpanel/cpkeyclt || missing "cPanel license refresh failed. Confirm your server IP has a valid cPanel license."
    else
      missing "Missing official cPanel license tool: /usr/local/cpanel/cpkeyclt"
    fi
  elif [ "$INSTALL_CPANEL" -eq 1 ]; then
    cd /home
    curl -o latest -L https://securedownloads.cpanel.net/latest
    sh latest
  else
    missing "cPanel is not installed. Re-run with --install-cpanel on a fresh supported OS."
  fi

  [ "$SKIP_SSL" -eq 1 ] && return
  if [ -x /usr/local/cpanel/bin/checkallsslcerts ]; then
    /usr/local/cpanel/bin/checkallsslcerts --verbose || missing "cPanel service SSL refresh failed."
  else
    missing "Missing cPanel SSL utility: /usr/local/cpanel/bin/checkallsslcerts"
  fi
}

log "Installing required tools"
install_tools
log "Checking server"
check_server
log "Configuring hostname and DNS"
configure_hostname
log "Configuring cPanel"
cpanel_work

echo
if [ -s "$REPORT" ]; then
  warn "Finished with missing items: $REPORT"
  cat "$REPORT"
  exit 3
fi

ok "cPanel VPS setup completed for $DOMAIN"
echo "WHM: https://$DOMAIN:2087"
