#!/bin/bash

# ============================================================
#
#   ██╗██╗  ██╗██╗   ██╗██╗   ██╗    ██╗  ██╗
#   ██║██║ ██╔╝╚██╗ ██╔╝╚██╗ ██╔╝    ╚██╗██╔╝
#   ██║█████╔╝  ╚████╔╝  ╚████╔╝      ╚███╔╝
#   ██║██╔═██╗   ╚██╔╝    ╚██╔╝       ██╔██╗
#   ██║██║  ██╗   ██║      ██║       ██╔╝ ██╗
#   ╚═╝╚═╝  ╚═╝   ╚═╝      ╚═╝       ╚═╝  ╚═╝
#
#    ██████╗██╗      █████╗ ██╗   ██╗██████╗ ███████╗
#   ██╔════╝██║     ██╔══██╗██║   ██║██╔══██╗██╔════╝
#   ██║     ██║     ███████║██║   ██║██║  ██║█████╗
#   ██║     ██║     ██╔══██║██║   ██║██║  ██║██╔══╝
#   ╚██████╗███████╗██║  ██║╚██████╔╝██████╔╝███████╗
#    ╚═════╝╚══════╝╚═╝  ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝
#
#   CyberPanel Auto Setup Script
#   By: IKYY X CLAUDE
#   Version: 2.0 (Fixed)
#   Support: Ubuntu 20.04, Ubuntu 22.04, AlmaLinux 8/9
#
# ============================================================

# --- Warna ---
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
WHITE='\033[1;37m'
NC='\033[0m'

# --- Fungsi Log ---
log_info()    { echo -e "${CYAN}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[OK]${NC} $1"; }
log_warning() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error()   { echo -e "${RED}[ERROR]${NC} $1"; }
log_step()    { echo -e "\n${WHITE}========================================${NC}"; echo -e "${WHITE} $1${NC}"; echo -e "${WHITE}========================================${NC}"; }

# --- Cek Root ---
if [[ $EUID -ne 0 ]]; then
    log_error "Script harus dijalankan sebagai root!"
    log_info "Coba: sudo bash Setup_CyberPanel.sh"
    exit 1
fi

# ============================================================
# FIX BUG 3: AUTO-DETECT OS — tidak perlu input manual
# ============================================================
if grep -qi "ubuntu 22.04" /etc/os-release; then
    OS="ubuntu"
    OS_NAME="Ubuntu 22.04"
    PKG="apt"
elif grep -qi "ubuntu 20.04" /etc/os-release; then
    OS="ubuntu"
    OS_NAME="Ubuntu 20.04"
    PKG="apt"
elif grep -qi "almalinux 9" /etc/os-release; then
    OS="almalinux"
    OS_NAME="AlmaLinux 9"
    PKG="dnf"
elif grep -qi "almalinux 8" /etc/os-release; then
    OS="almalinux"
    OS_NAME="AlmaLinux 8"
    PKG="dnf"
else
    log_error "OS tidak didukung CyberPanel!"
    log_error "OS yang didukung: Ubuntu 20.04, Ubuntu 22.04, AlmaLinux 8, AlmaLinux 9"
    log_info  "OS terdeteksi: $(grep PRETTY_NAME /etc/os-release | cut -d= -f2 | tr -d '\"')"
    exit 1
fi

clear
echo -e "${CYAN}"
cat << "EOF"
  ██╗██╗  ██╗██╗   ██╗██╗   ██╗    ██╗  ██╗
  ██║██║ ██╔╝╚██╗ ██╔╝╚██╗ ██╔╝    ╚██╗██╔╝
  ██║█████╔╝  ╚████╔╝  ╚████╔╝      ╚███╔╝ 
  ██║██╔═██╗   ╚██╔╝    ╚██╔╝       ██╔██╗ 
  ██║██║  ██╗   ██║      ██║       ██╔╝ ██╗
  ╚═╝╚═╝  ╚═╝   ╚═╝      ╚═╝       ╚═╝  ╚═╝
EOF
echo -e "${NC}"
echo -e "${WHITE}  CyberPanel Auto Setup | by IKYY x CLAUDE${NC}"
echo -e "${CYAN}  OS Terdeteksi: ${OS_NAME}${NC}"
echo -e "${YELLOW}  Bismillah, semoga lancar dan berkah 🤲${NC}"
echo ""
sleep 2

# ============================================================
# STEP 1 - Update & Upgrade
# ============================================================
log_step "STEP 1: Update & Upgrade System"

if [[ "$OS" == "ubuntu" ]]; then
    log_info "Mengupdate package list..."
    apt update -y -qq
    log_info "Mengupgrade package..."
    # FIX BUG 7: DEBIAN_FRONTEND=noninteractive agar tidak stuck interaktif
    DEBIAN_FRONTEND=noninteractive apt upgrade -y -qq
    log_info "Install dependency dasar..."
    apt install -y -qq curl wget git unzip software-properties-common ufw
else
    log_info "Mengupdate package list..."
    dnf update -y -q
    log_info "Install dependency dasar..."
    dnf install -y -q curl wget git unzip
fi

log_success "System up to date!"

# ============================================================
# STEP 2 - Set Timezone WIB
# ============================================================
log_step "STEP 2: Set Timezone ke WIB (Asia/Jakarta)"
timedatectl set-timezone Asia/Jakarta
log_success "Timezone: $(timedatectl | grep 'Time zone')"

# ============================================================
# STEP 3 - Optimasi Swap
# FIX BUG 6: Cek semua swap yang ada, bukan hanya /swapfile
# ============================================================
log_step "STEP 3: Setup Swap 2GB"
if [[ $(swapon --show | wc -l) -gt 0 ]]; then
    EXISTING_SWAP=$(swapon --show --noheadings | awk '{print $1, $3}' | head -1)
    log_warning "Swap sudah ada (${EXISTING_SWAP}), skip"
else
    fallocate -l 2G /swapfile
    chmod 600 /swapfile
    mkswap /swapfile
    swapon /swapfile
    echo '/swapfile none swap sw 0 0' >> /etc/fstab
    log_success "Swap 2GB aktif"
fi

# ============================================================
# STEP 4 - Konfigurasi Firewall
# FIX BUG 1: Tanya SSH port dulu sebelum setup firewall
# ============================================================
log_step "STEP 4: Konfigurasi Firewall"

echo ""
read -p "  SSH Port yang dipakai (default: 22): " SSH_PORT
SSH_PORT=${SSH_PORT:-22}

log_info "Membuka port yang dibutuhkan CyberPanel..."

if [[ "$OS" == "ubuntu" ]]; then
    ufw allow ${SSH_PORT}/tcp  # SSH — FIX BUG 1: pakai port yang diinput
    ufw allow 80/tcp           # HTTP
    ufw allow 443/tcp          # HTTPS
    ufw allow 8090/tcp         # CyberPanel Dashboard
    ufw allow 8443/tcp         # CyberPanel SSL Dashboard
    ufw allow 21/tcp           # FTP
    ufw allow 40110:40210/tcp  # FTP Passive
    # FIX BUG 2: Tidak allow MySQL dari awal, langsung skip
    ufw --force enable
    log_success "UFW Firewall dikonfigurasi!"
    ufw status
else
    systemctl enable firewalld --now
    firewall-cmd --permanent --add-port=${SSH_PORT}/tcp
    firewall-cmd --permanent --add-port=80/tcp
    firewall-cmd --permanent --add-port=443/tcp
    firewall-cmd --permanent --add-port=8090/tcp
    firewall-cmd --permanent --add-port=8443/tcp
    firewall-cmd --permanent --add-port=21/tcp
    firewall-cmd --permanent --add-port=40110-40210/tcp
    firewall-cmd --reload
    log_success "Firewalld dikonfigurasi!"
fi

# ============================================================
# STEP 5 - Install CyberPanel
# FIX BUG 4: Tambah timeout dan verifikasi download
# ============================================================
log_step "STEP 5: Install CyberPanel (OpenLiteSpeed)"
echo ""
log_warning "PERHATIAN! Installer akan berjalan interaktif."
echo -e "${YELLOW}Jawab pertanyaan sebagai berikut:${NC}"
echo ""
echo -e "  ${WHITE}►${NC} Pilih menu install  → ketik ${GREEN}1${NC} (Install CyberPanel)"
echo -e "  ${WHITE}►${NC} Pilih web server    → ketik ${GREEN}1${NC} (OpenLiteSpeed - FREE)"
echo -e "  ${WHITE}►${NC} Full service        → ketik ${GREEN}y${NC}"
echo -e "  ${WHITE}►${NC} Memcached           → ketik ${GREEN}y${NC}"
echo -e "  ${WHITE}►${NC} Redis               → ketik ${GREEN}y${NC} ← PENTING untuk Laravel!"
echo -e "  ${WHITE}►${NC} Remote MySQL        → ketik ${GREEN}n${NC}"
echo ""
read -p "Siap mulai install CyberPanel? (y/n): " READY
if [[ "$READY" != "y" ]]; then
    log_warning "Install dibatalkan."
    exit 0
fi

log_info "Mendownload installer CyberPanel..."

# FIX BUG 4: Download dulu, verifikasi, baru eksekusi
INSTALLER="/tmp/cyberpanel_install.sh"
if curl --max-time 60 -s -o "$INSTALLER" https://cyberpanel.net/install.sh; then
    if [[ -s "$INSTALLER" ]]; then
        log_success "Installer berhasil didownload"
        bash "$INSTALLER"
    else
        log_error "File installer kosong! Coba download manual:"
        log_error "curl https://cyberpanel.net/install.sh | bash"
        exit 1
    fi
else
    log_warning "curl gagal, mencoba wget..."
    if wget --timeout=60 -q -O "$INSTALLER" https://cyberpanel.net/install.sh; then
        if [[ -s "$INSTALLER" ]]; then
            log_success "Installer berhasil didownload via wget"
            bash "$INSTALLER"
        else
            log_error "File installer kosong!"
            exit 1
        fi
    else
        log_error "Gagal download installer CyberPanel. Cek koneksi internet!"
        exit 1
    fi
fi

rm -f "$INSTALLER"

# ============================================================
# STEP 6 - Post Install
# FIX BUG 2: Hapus rule MySQL dengan delete bukan deny
# ============================================================
log_step "STEP 6: Post-Install Configuration"

log_info "Memastikan port MySQL tidak terbuka dari publik..."
if [[ "$OS" == "ubuntu" ]]; then
    # FIX BUG 2: delete allow, bukan deny
    ufw delete allow 3306/tcp 2>/dev/null || true
    ufw reload
else
    firewall-cmd --permanent --remove-port=3306/tcp 2>/dev/null || true
    firewall-cmd --reload
fi
log_success "Port MySQL (3306) tidak terbuka dari publik"

# Cek service berjalan
log_info "Mengecek status service..."
systemctl is-active --quiet lscpd    && log_success "CyberPanel (lscpd) berjalan"  || log_warning "CyberPanel belum aktif — mungkin butuh beberapa menit"
systemctl is-active --quiet lsws     && log_success "OpenLiteSpeed berjalan"        || log_warning "OpenLiteSpeed belum aktif"
systemctl is-active --quiet redis-server && log_success "Redis berjalan"            || log_warning "Redis belum aktif"
systemctl is-active --quiet memcached    && log_success "Memcached berjalan"        || log_warning "Memcached belum aktif"

if [[ "$OS" == "ubuntu" ]]; then
    systemctl is-active --quiet mysql 2>/dev/null || systemctl is-active --quiet mariadb 2>/dev/null \
        && log_success "MySQL/MariaDB berjalan" || log_warning "MySQL/MariaDB belum aktif"
else
    systemctl is-active --quiet mysqld 2>/dev/null \
        && log_success "MySQL berjalan" || log_warning "MySQL belum aktif"
fi

# ============================================================
# STEP 7 - Health Check
# FIX BUG 8: Verifikasi CyberPanel benar-benar bisa diakses
# ============================================================
log_step "STEP 7: Health Check"

log_info "Menunggu CyberPanel siap (30 detik)..."
sleep 30

HEALTH_OK=true

if ! systemctl is-active --quiet lscpd 2>/dev/null; then
    log_warning "lscpd tidak aktif — coba: systemctl start lscpd"
    HEALTH_OK=false
fi

if ! systemctl is-active --quiet lsws 2>/dev/null; then
    log_warning "OpenLiteSpeed tidak aktif — coba: systemctl start lsws"
    HEALTH_OK=false
fi

# Cek port 8090 listen
if ss -tlnp 2>/dev/null | grep -q ":8090"; then
    log_success "Port 8090 aktif — CyberPanel siap diakses"
else
    log_warning "Port 8090 belum listen — CyberPanel mungkin masih starting"
    HEALTH_OK=false
fi

if [[ "$HEALTH_OK" == true ]]; then
    log_success "Health check passed — semua service berjalan normal"
else
    log_warning "Beberapa service belum aktif. Tunggu 1-2 menit lalu cek manual:"
    log_info "systemctl status lscpd lsws"
fi

# ============================================================
# STEP 8 - Info Akses
# FIX BUG 5: SERVER_IP dengan timeout dan fallback yang benar
# ============================================================
log_step "STEP 8: Informasi Akses"

# FIX BUG 5: Tambah timeout dan pastikan dapat IPv4
SERVER_IP=$(curl -s --max-time 5 -4 ifconfig.me 2>/dev/null || \
            curl -s --max-time 5 -4 icanhazip.com 2>/dev/null || \
            curl -s --max-time 5 api.ipify.org 2>/dev/null || \
            hostname -I | awk '{for(i=1;i<=NF;i++) if($i !~ /:/) {print $i; exit}}')

echo ""
echo -e "${GREEN}╔══════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║      CYBERPANEL BERHASIL DIINSTALL! 🎉       ║${NC}"
echo -e "${GREEN}╠══════════════════════════════════════════════╣${NC}"
echo -e "${GREEN}║${NC}  OS          : ${CYAN}${OS_NAME}${NC}"
echo -e "${GREEN}║${NC}  Dashboard   : ${CYAN}https://${SERVER_IP}:8090${NC}"
echo -e "${GREEN}║${NC}  Username    : ${WHITE}admin${NC}"
echo -e "${GREEN}║${NC}  Password    : ${YELLOW}(lihat output installer di atas)${NC}"
echo -e "${GREEN}║${NC}  SSH Port    : ${WHITE}${SSH_PORT}${NC}"
echo -e "${GREEN}╠══════════════════════════════════════════════╣${NC}"
echo -e "${GREEN}║${NC}  ${YELLOW}⚠ Segera ganti password setelah login!${NC}"
echo -e "${GREEN}║${NC}  ${YELLOW}⚠ Simpan password di tempat aman!${NC}"
echo -e "${GREEN}╚══════════════════════════════════════════════╝${NC}"
echo ""
echo -e "${CYAN}Next Steps:${NC}"
echo -e "  1. Login ke CyberPanel di browser"
echo -e "  2. Buat website baru"
echo -e "  3. Setup PHP 8.2 & Composer"
echo -e "  4. Deploy aplikasi Laravel"
echo ""
echo -e "${YELLOW}  Alhamdulillah, setup selesai! Semoga sukses & berkah 🚀🤲${NC}"
echo ""
