#!/usr/bin/env bash
# ==============================================================================
# ZOI - VPS Hosting Management & Installation Toolkit
# Single-Command Production Installer
# ==============================================================================

set -eo pipefail

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m' # No Color

ZOI_VERSION="1.0.0"
ZOI_BIN_DIR="/usr/local/bin"
ZOI_CONFIG_DIR="/etc/zoi"
ZOI_LOG_DIR="/var/log/zoi"
ZOI_BACKUP_DIR="/var/backups/zoi"

DEFAULT_DOWNLOAD_BASE="https://zoi-v6.zoimc.fun/dist"

# Check root privilege
if [ "$(id -u)" -ne 0 ]; then
    echo -e "${RED}${BOLD}Error:${NC} ZOI installer must be run as root (use sudo or switch to root)." >&2
    exit 1
fi

echo -e "${PURPLE}${BOLD}"
cat << 'EOF'
╔════════════════════════════════════════════════════════════╗
║                         Z O I                              ║
║              VPS Hosting Management Suite                  ║
║                  Production Installer                      ║
╚════════════════════════════════════════════════════════════╝
EOF
echo -e "${NC}"

echo -e "${CYAN}▶ Step 1/6: Detecting Operating System & Architecture...${NC}"

# Detect OS
if [ ! -f /etc/os-release ]; then
    echo -e "${RED}Error: /etc/os-release not found. Unsupported system.${NC}" >&2
    exit 1
fi

. /etc/os-release

OS_ID=$(echo "$ID" | tr '[:upper:]' '[:lower:]')
OS_VER="$VERSION_ID"

echo -e "  Host OS: ${BOLD}${PRETTY_NAME:-$OS_ID $OS_VER}${NC}"

SUPPORTED=false
if [ "$OS_ID" = "ubuntu" ]; then
    if [ "$OS_VER" = "22.04" ] || [ "$OS_VER" = "24.04" ]; then
        SUPPORTED=true
    fi
elif [ "$OS_ID" = "debian" ]; then
    if [ "$OS_VER" = "12" ] || [ "$OS_VER" = "13" ]; then
        SUPPORTED=true
    fi
fi

if [ "$SUPPORTED" != "true" ]; then
    echo -e "${RED}${BOLD}✗ Unsupported Operating System:${NC} $OS_ID $OS_VER" >&2
    echo -e "  ZOI officially supports:" >&2
    echo -e "    - Ubuntu 22.04 LTS (Jammy)" >&2
    echo -e "    - Ubuntu 24.04 LTS (Noble)" >&2
    echo -e "    - Debian 12 (Bookworm)" >&2
    echo -e "    - Debian 13 (Trixie)" >&2
    echo -e "${YELLOW}Installation aborted to protect your server.${NC}" >&2
    exit 1
fi
echo -e "  ${GREEN}✓ Operating system verified${NC}"

# Detect Architecture
ARCH=$(uname -m)
case "$ARCH" in
    x86_64|amd64)
        ZOI_ARCH="amd64"
        ;;
    aarch64|arm64)
        ZOI_ARCH="arm64"
        ;;
    *)
        echo -e "${RED}✗ Unsupported architecture: $ARCH (ZOI supports x86_64 and aarch64)${NC}" >&2
        exit 1
        ;;
esac
echo -e "  Architecture: ${BOLD}${ZOI_ARCH}${NC} ${GREEN}✓${NC}"

echo -e "\n${CYAN}▶ Step 2/6: Installing Base System Prerequisites...${NC}"
export DEBIAN_FRONTEND=noninteractive
apt-get update -qq
apt-get install -y -qq curl wget tar gzip ca-certificates ufw > /dev/null
echo -e "  ${GREEN}✓ Base packages installed (curl, wget, tar, ca-certificates, ufw)${NC}"

echo -e "\n${CYAN}▶ Step 3/6: Setting Up System Directories & Permissions...${NC}"
mkdir -p "$ZOI_CONFIG_DIR"
mkdir -p "$ZOI_LOG_DIR"
mkdir -p "$ZOI_BACKUP_DIR"
mkdir -p "$ZOI_BACKUP_DIR/nginx"
mkdir -p "$ZOI_BACKUP_DIR/wings"
mkdir -p "$ZOI_BACKUP_DIR/ssh"

chmod 700 "$ZOI_CONFIG_DIR"
chmod 750 "$ZOI_LOG_DIR"
chmod 700 "$ZOI_BACKUP_DIR"
echo -e "  ${GREEN}✓ Secure directory tree initialized (/etc/zoi, /var/log/zoi, /var/backups/zoi)${NC}"

echo -e "\n${CYAN}▶ Step 4/6: Deploying ZOI Binary...${NC}"
INSTALL_SOURCE=""
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Check if local pre-compiled binary exists
if [ -f "$SCRIPT_DIR/dist/zoi-linux-$ZOI_ARCH" ]; then
    echo -e "  Using local build from $SCRIPT_DIR/dist/zoi-linux-$ZOI_ARCH"
    cp "$SCRIPT_DIR/dist/zoi-linux-$ZOI_ARCH" "$ZOI_BIN_DIR/zoi"
elif [ -f "$SCRIPT_DIR/zoi-linux-$ZOI_ARCH" ]; then
    echo -e "  Using local binary $SCRIPT_DIR/zoi-linux-$ZOI_ARCH"
    cp "$SCRIPT_DIR/zoi-linux-$ZOI_ARCH" "$ZOI_BIN_DIR/zoi"
else
    # Download binary from release endpoint
    DOWNLOAD_URL="${ZOI_MIRROR:-$DEFAULT_DOWNLOAD_BASE}/zoi-linux-$ZOI_ARCH"
    echo -e "  Downloading ZOI from: ${BOLD}$DOWNLOAD_URL${NC}"
    curl -fsSL "$DOWNLOAD_URL" -o "$ZOI_BIN_DIR/zoi" || {
        echo -e "${RED}✗ Failed to download ZOI binary from $DOWNLOAD_URL${NC}" >&2
        exit 1
    }
fi

chmod 755 "$ZOI_BIN_DIR/zoi"
echo -e "  ${GREEN}✓ Binary installed to $ZOI_BIN_DIR/zoi${NC}"

echo -e "\n${CYAN}▶ Step 5/6: Initializing Configuration...${NC}"
if [ ! -f "$ZOI_CONFIG_DIR/config.yml" ]; then
    cat << EOF > "$ZOI_CONFIG_DIR/config.yml"
version: "1.0.0"
environment: "production"
installed_at: $(date -u +"%Y-%m-%dT%H:%M:%SZ")
updated_at: $(date -u +"%Y-%m-%dT%H:%M:%SZ")
panel:
  installed: false
  fqdn: ""
  ssl_enabled: true
  php_version: "8.3"
  database_name: "panel"
  database_user: "pterodactyl"
  webserver: "nginx"
wings:
  installed: false
  fqdn: ""
  ssl_enabled: true
  api_port: 8080
  sftp_port: 2022
  configured: false
security:
  ufw_enabled: true
  ssh_port: 22
  ssh_hardened: false
  fail2ban_enabled: true
  ddos_tuned: true
  allowed_ports: [22, 80, 443, 8080, 2022]
backups:
  storage_dir: "/var/backups/zoi"
  schedule: "daily"
  retention_days: 7
  cron_expr: "0 2 * * *"
rate_limiting:
  enabled: true
  reqs_per_sec: 10
  burst: 20
  max_connections: 50
  whitelist_nodes: ["127.0.0.1", "::1"]
EOF
    chmod 600 "$ZOI_CONFIG_DIR/config.yml"
    echo -e "  ${GREEN}✓ Initialized default configuration at $ZOI_CONFIG_DIR/config.yml (chmod 600)${NC}"
else
    echo -e "  ${YELLOW}Existing configuration detected at $ZOI_CONFIG_DIR/config.yml, preserving settings.${NC}"
fi

echo -e "\n${CYAN}▶ Step 6/6: Running System Pre-flight Doctor Check...${NC}"
"$ZOI_BIN_DIR/zoi" doctor || true

echo -e "${GREEN}${BOLD}"
cat << 'EOF'
╔════════════════════════════════════════════════════════════╗
║                    ZOI INSTALLED                           ║
╠════════════════════════════════════════════════════════════╣
║                                                            ║
║  Version:       1.0.0                                      ║
║  Status:        ● Healthy                                  ║
║                                                            ║
║  Run:           zoi                                        ║
║  Health:        zoi doctor                                 ║
║  Help:          zoi --help                                 ║
║                                                            ║
╚════════════════════════════════════════════════════════════╝
EOF
echo -e "${NC}"

echo -e "To launch the interactive control panel, run:  ${BOLD}${CYAN}zoi${NC}"
echo -e "To install Pterodactyl Panel on your domain:     ${BOLD}${CYAN}zoi panel install --fqdn zoi-v6.zoimc.fun --ssl${NC}"
echo -e "To install Pterodactyl Wings node:              ${BOLD}${CYAN}zoi wings install --fqdn node1.zoimc.fun --ssl${NC}"
echo ""
