#!/bin/bash

# ============================================================
#   UNIVERSAL AUTO TROUBLESHOOT & FIX SCRIPT
#   Cover : WHM/cPanel, CyberPanel, Minecraft, Hardening
#   OS    : AlmaLinux 9 / Ubuntu 22 / Ubuntu 24
#   Author: IKYY x CLAUDE
#   Version: 2.0 (Fixed)
# ============================================================

# --- WARNA ---
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
PURPLE='\033[0;35m'
GRAY='\033[0;37m'
BOLD='\033[1m'
NC='\033[0m'

# --- BANNER ---
clear
echo -e "${CYAN}${BOLD}"
echo "  ██╗██╗  ██╗██╗   ██╗██╗   ██╗    ██╗  ██╗    ████████╗██████╗  ██████╗ "
echo "  ██║██║ ██╔╝╚██╗ ██╔╝╚██╗ ██╔╝    ╚██╗██╔╝    ╚══██╔══╝██╔══██╗██╔════╝ "
echo "  ██║█████╔╝  ╚████╔╝  ╚████╔╝      ╚███╔╝        ██║   ██████╔╝╚█████╗  "
echo "  ██║██╔═██╗   ╚██╔╝    ╚██╔╝       ██╔██╗        ██║   ██╔══██╗ ╚═══██╗ "
echo "  ██║██║  ██╗   ██║      ██║       ██╔╝ ██╗       ██║   ██║  ██║██████╔╝ "
echo "  ╚═╝╚═╝  ╚═╝   ╚═╝      ╚═╝       ╚═╝  ╚═╝       ╚═╝   ╚═╝  ╚═╝╚═════╝  "
echo -e "${NC}"
echo -e "${YELLOW}  Universal Auto Troubleshoot & Fix | by IKYY x CLAUDE${NC}"
echo -e "${CYAN}  ================================================================${NC}"
echo ""

# --- CEK ROOT ---
if [[ $EUID -ne 0 ]]; then
  echo -e "${RED}[ERROR] Script ini harus dijalankan sebagai root!${NC}"
  exit 1
fi

# --- DETEKSI OS ---
if grep -qi "almalinux" /etc/os-release; then
  OS="almalinux"
  OS_NAME="AlmaLinux"
  PKG="dnf"
  FIREWALL="firewalld"
elif grep -qi "ubuntu" /etc/os-release; then
  OS="ubuntu"
  OS_NAME="Ubuntu"
  PKG="apt"
  FIREWALL="ufw"
else
  echo -e "${RED}[ERROR] OS tidak didukung!${NC}"
  exit 1
fi

# --- LOG ---
LOG_FILE="/var/log/troubleshoot_ikyy.log"
REPORT_FILE="/var/log/troubleshoot_report_$(date +%Y%m%d_%H%M%S).log"
exec > >(tee -a $LOG_FILE) 2>&1
echo "=== Troubleshoot dimulai: $(date) ===" >> $LOG_FILE

# --- COUNTER ---
# FIX T12 & T13: Counter logic diperbaiki — TOTAL_ISSUES = FIXED + MANUAL
TOTAL_ISSUES=0
FIXED_ISSUES=0
MANUAL_ISSUES=0

# --- FUNGSI HELPER ---
log_ok()     { echo -e "  ${GREEN}✅ $1${NC}"; echo "[OK] $1" >> $REPORT_FILE; }
# FIX T12: log_warn naikkan TOTAL_ISSUES
log_warn()   { echo -e "  ${YELLOW}⚠️  $1${NC}"; echo "[WARN] $1" >> $REPORT_FILE; TOTAL_ISSUES=$((TOTAL_ISSUES+1)); }
# FIX T13: log_fixed dan log_manual juga naikkan TOTAL_ISSUES
log_fixed()  {
  echo -e "  ${CYAN}🔧 $1 → AUTO FIXED ✅${NC}"
  echo "[FIXED] $1" >> $REPORT_FILE
  FIXED_ISSUES=$((FIXED_ISSUES+1))
  TOTAL_ISSUES=$((TOTAL_ISSUES+1))
  # Kirim notif Telegram jika config tersedia — FIX T3
  _notify_telegram "🔧 <b>AUTO-FIX</b>
✅ $1
⏰ $(date '+%Y-%m-%d %H:%M:%S')
🖥 Server: $(hostname)"
}
log_manual() {
  echo -e "  ${RED}❌ $1 → PERLU TINDAKAN MANUAL${NC}"
  echo "[MANUAL] $1" >> $REPORT_FILE
  MANUAL_ISSUES=$((MANUAL_ISSUES+1))
  TOTAL_ISSUES=$((TOTAL_ISSUES+1))
  # Kirim notif Telegram jika config tersedia — FIX T3
  _notify_telegram "❌ <b>PERLU TINDAKAN MANUAL</b>
$1
⏰ $(date '+%Y-%m-%d %H:%M:%S')
🖥 Server: $(hostname)"
}
log_info()   { echo -e "  ${PURPLE}ℹ  $1${NC}"; }
section()    { echo ""; echo -e "${CYAN}${BOLD}[ $1 ]${NC}"; echo -e "${CYAN}$(printf '─%.0s' {1..60})${NC}"; }

# FIX T3: Fungsi notifikasi Telegram (load dari config monitoring jika ada)
_notify_telegram() {
  local MSG="$1"
  local CONFIG="/opt/ikyy_monitor/config.conf"
  if [[ -f "$CONFIG" ]]; then
    source "$CONFIG" 2>/dev/null
    if [[ -n "$TG_TOKEN" && -n "$TG_CHAT_ID" ]]; then
      curl -s -X POST "https://api.telegram.org/bot${TG_TOKEN}/sendMessage" \
        --data-urlencode "chat_id=${TG_CHAT_ID}" \
        --data-urlencode "text=${MSG}" \
        --data-urlencode "parse_mode=HTML" > /dev/null 2>&1
    fi
  fi
}

# ============================================================
# FASE 1: SCAN & DETEKSI SERVICE
# ============================================================
section "FASE 1: SCAN & DETEKSI SERVICE"

HAS_CPANEL=false
HAS_CYBERPANEL=false
HAS_MINECRAFT=false
HAS_HARDENING=false
HAS_FAIL2BAN=false
HAS_FIREWALL=false
HAS_MONITOR=false

# Deteksi WHM/cPanel
if [[ -d "/usr/local/cpanel" ]]; then
  HAS_CPANEL=true
  log_info "WHM/cPanel terdeteksi"
fi

# Deteksi CyberPanel
if [[ -d "/usr/local/CyberCP" ]] || [[ -f "/usr/bin/cyberpanel" ]]; then
  HAS_CYBERPANEL=true
  log_info "CyberPanel terdeteksi"
fi

# Deteksi Minecraft
if [[ -f "/home/minecraft/server/paper.jar" ]] || systemctl is-active --quiet minecraft 2>/dev/null; then
  HAS_MINECRAFT=true
  log_info "Minecraft Server terdeteksi"
fi

# FIX T14: Deteksi hardening pakai cek yang lebih reliable
if [[ -f "/var/log/hardening_ikyy.log" ]] || \
   [[ -f "/etc/sysctl.d/99-hardening-ikyy.conf" ]] || \
   [[ -f "/etc/fail2ban/jail.local" ]]; then
  HAS_HARDENING=true
  log_info "Hardening terdeteksi"
fi

# Deteksi Fail2Ban
if command -v fail2ban-client &>/dev/null; then
  HAS_FAIL2BAN=true
  log_info "Fail2Ban terdeteksi"
fi

# Deteksi Firewall
if [[ "$OS" == "almalinux" ]] && systemctl is-active --quiet firewalld; then
  HAS_FIREWALL=true
  log_info "Firewalld terdeteksi"
elif [[ "$OS" == "ubuntu" ]] && command -v ufw &>/dev/null; then
  HAS_FIREWALL=true
  log_info "UFW terdeteksi"
fi

# FIX T10: Deteksi ikyy_monitor service
if systemctl is-active --quiet ikyy_monitor 2>/dev/null || \
   systemctl is-active --quiet ikyy_bot 2>/dev/null; then
  HAS_MONITOR=true
  log_info "IKYY Monitor terdeteksi"
fi

echo ""
echo -e "  OS           : ${CYAN}${OS_NAME}${NC}"
# FIX T2: Tambah $GRAY ke definisi warna di atas
echo -e "  WHM/cPanel   : $([ "$HAS_CPANEL" == true ] && echo -e "${GREEN}✅ Ada${NC}" || echo -e "${GRAY}— Tidak ada${NC}")"
echo -e "  CyberPanel   : $([ "$HAS_CYBERPANEL" == true ] && echo -e "${GREEN}✅ Ada${NC}" || echo -e "${GRAY}— Tidak ada${NC}")"
echo -e "  Minecraft    : $([ "$HAS_MINECRAFT" == true ] && echo -e "${GREEN}✅ Ada${NC}" || echo -e "${GRAY}— Tidak ada${NC}")"
echo -e "  Hardening    : $([ "$HAS_HARDENING" == true ] && echo -e "${GREEN}✅ Ada${NC}" || echo -e "${GRAY}— Tidak ada${NC}")"
echo -e "  Fail2Ban     : $([ "$HAS_FAIL2BAN" == true ] && echo -e "${GREEN}✅ Ada${NC}" || echo -e "${GRAY}— Tidak ada${NC}")"
echo -e "  Monitor      : $([ "$HAS_MONITOR" == true ] && echo -e "${GREEN}✅ Ada${NC}" || echo -e "${GRAY}— Tidak ada${NC}")"
echo ""

# ============================================================
# FASE 2: CEK SISTEM DASAR
# ============================================================
section "FASE 2: CEK SISTEM DASAR"

# Koneksi Internet — FIX T6: Tambah timeout ping
echo -e "\n  ${BOLD}🌐 Koneksi Internet${NC}"
if ping -c 1 -W 5 8.8.8.8 &>/dev/null; then
  log_ok "Koneksi internet OK"
else
  log_warn "Tidak ada koneksi internet"
  log_manual "Koneksi internet bermasalah — cek provider/router VPS lo"
fi

# RAM — FIX T16: Hapus RAM_FREE yang tidak dipakai
echo -e "\n  ${BOLD}💾 RAM${NC}"
RAM_TOTAL=$(free -m | awk '/^Mem:/{print $2}')
RAM_USED=$(free -m | awk '/^Mem:/{print $3}')
RAM_PCT=$((RAM_USED * 100 / RAM_TOTAL))

if [[ $RAM_PCT -lt 85 ]]; then
  log_ok "RAM OK — ${RAM_USED}MB / ${RAM_TOTAL}MB (${RAM_PCT}% used)"
elif [[ $RAM_PCT -lt 95 ]]; then
  log_warn "RAM tinggi — ${RAM_USED}MB / ${RAM_TOTAL}MB (${RAM_PCT}% used)"
  log_manual "RAM hampir penuh. Pertimbangkan upgrade VPS atau kurangi service"
else
  log_warn "RAM kritis — ${RAM_USED}MB / ${RAM_TOTAL}MB (${RAM_PCT}% used)"
  sync && echo 3 > /proc/sys/vm/drop_caches
  log_fixed "Cache RAM dibersihkan otomatis"
fi

# Disk
echo -e "\n  ${BOLD}💿 Disk${NC}"
DISK_PCT=$(df / | awk 'NR==2{print $5}' | tr -d '%')
DISK_FREE=$(df -h / | awk 'NR==2{print $4}')

if [[ $DISK_PCT -lt 80 ]]; then
  log_ok "Disk OK — ${DISK_FREE} tersisa (${DISK_PCT}% used)"
elif [[ $DISK_PCT -lt 90 ]]; then
  log_warn "Disk mulai penuh — ${DISK_FREE} tersisa (${DISK_PCT}% used)"
  find /var/log -name "*.log" -mtime +30 -exec rm -f {} \; 2>/dev/null
  journalctl --vacuum-time=7d &>/dev/null
  log_fixed "Log lama (>30 hari) dibersihkan otomatis"
else
  log_warn "Disk sangat penuh — ${DISK_FREE} tersisa (${DISK_PCT}% used)"
  find /var/log -name "*.log" -mtime +7 -exec rm -f {} \; 2>/dev/null
  find /tmp -mtime +3 -exec rm -rf {} \; 2>/dev/null
  journalctl --vacuum-time=3d &>/dev/null
  log_fixed "Log & temp files dibersihkan otomatis"
  if [[ $(df / | awk 'NR==2{print $5}' | tr -d '%') -gt 90 ]]; then
    log_manual "Disk masih penuh setelah cleanup. Hapus file besar manual: du -sh /* | sort -rh | head -20"
  fi
fi

# CPU Load
echo -e "\n  ${BOLD}⚡ CPU Load${NC}"
CPU_LOAD=$(uptime | awk -F'load average:' '{print $2}' | awk -F',' '{print $1}' | tr -d ' ')
CPU_CORES=$(nproc)
CPU_LOAD_INT=$(echo "$CPU_LOAD" | cut -d. -f1)

if [[ $CPU_LOAD_INT -lt $CPU_CORES ]]; then
  log_ok "CPU load normal — Load: ${CPU_LOAD} | Core: ${CPU_CORES}"
else
  log_warn "CPU load tinggi — Load: ${CPU_LOAD} | Core: ${CPU_CORES}"
  log_manual "CPU overloaded. Cek proses berat: top atau htop"
fi

# ============================================================
# CEK WHM/cPANEL
# ============================================================
if [[ "$HAS_CPANEL" == true ]]; then
  section "FASE 2: CEK WHM/cPANEL"

  # FIX T8: Service check tanpa checkperlmod yang misleading
  echo -e "\n  ${BOLD}🔧 cPanel Services${NC}"
  for SVC in cpanel whm cpsrvd; do
    if systemctl is-active --quiet $SVC 2>/dev/null; then
      log_ok "Service ${SVC} berjalan"
    else
      log_warn "Service ${SVC} mati"
      /usr/local/cpanel/scripts/restartsrv_$SVC &>/dev/null || systemctl restart $SVC &>/dev/null
      sleep 3
      if systemctl is-active --quiet $SVC 2>/dev/null; then
        log_fixed "Service ${SVC} berhasil direstart"
      else
        log_manual "Service ${SVC} gagal restart — cek: /usr/local/cpanel/logs/"
      fi
    fi
  done

  # FIX T4: Port cPanel — reload firewall sekali setelah semua port dibuka
  echo -e "\n  ${BOLD}🔌 Port WHM/cPanel${NC}"
  NEED_FW_RELOAD=false
  for PORT in 2082 2083 2086 2087 2095 2096; do
    # FIX T5: check_port_open dengan protokol eksplisit
    if check_port_open $PORT tcp; then
      log_ok "Port ${PORT}/tcp terbuka"
    else
      log_warn "Port ${PORT}/tcp tertutup"
      if [[ "$OS" == "almalinux" ]]; then
        firewall-cmd --permanent --add-port=${PORT}/tcp &>/dev/null
        NEED_FW_RELOAD=true
      else
        ufw allow ${PORT}/tcp &>/dev/null
      fi
      log_fixed "Port ${PORT}/tcp dibuka di firewall"
    fi
  done
  # Reload sekali di akhir
  if [[ "$NEED_FW_RELOAD" == true ]]; then
    firewall-cmd --reload &>/dev/null
  fi

  # Apache/Nginx — FIX T9: Verifikasi restart berhasil
  echo -e "\n  ${BOLD}🌐 Web Server${NC}"
  if systemctl is-active --quiet httpd 2>/dev/null || systemctl is-active --quiet apache2 2>/dev/null; then
    log_ok "Apache/HTTPD berjalan"
  else
    log_warn "Apache/HTTPD mati"
    systemctl restart httpd 2>/dev/null || systemctl restart apache2 2>/dev/null
    sleep 3
    if systemctl is-active --quiet httpd 2>/dev/null || systemctl is-active --quiet apache2 2>/dev/null; then
      log_fixed "Apache direstart otomatis"
    else
      log_manual "Apache gagal restart — cek: journalctl -u httpd -n 50"
    fi
  fi

  # MySQL/MariaDB
  echo -e "\n  ${BOLD}🗄 Database${NC}"
  if systemctl is-active --quiet mysql 2>/dev/null || systemctl is-active --quiet mariadb 2>/dev/null; then
    log_ok "MySQL/MariaDB berjalan"
  else
    log_warn "MySQL/MariaDB mati"
    systemctl restart mysql 2>/dev/null || systemctl restart mariadb 2>/dev/null
    sleep 3
    if systemctl is-active --quiet mysql 2>/dev/null || systemctl is-active --quiet mariadb 2>/dev/null; then
      log_fixed "MySQL/MariaDB direstart"
    else
      log_manual "MySQL/MariaDB gagal start — cek: journalctl -u mysql -n 50"
    fi
  fi
fi

# ============================================================
# CEK CYBERPANEL
# ============================================================
if [[ "$HAS_CYBERPANEL" == true ]]; then
  section "FASE 2: CEK CYBERPANEL"

  echo -e "\n  ${BOLD}🔧 CyberPanel Services${NC}"
  for SVC in lscpd lsws; do
    if systemctl is-active --quiet $SVC 2>/dev/null; then
      log_ok "Service ${SVC} berjalan"
    else
      log_warn "Service ${SVC} mati"
      systemctl restart $SVC &>/dev/null
      sleep 3
      if systemctl is-active --quiet $SVC 2>/dev/null; then
        log_fixed "Service ${SVC} direstart"
      else
        log_manual "Service ${SVC} gagal restart — cek: journalctl -u ${SVC} -n 50"
      fi
    fi
  done

  # FIX T4: Port CyberPanel — reload sekali di akhir
  echo -e "\n  ${BOLD}🔌 Port CyberPanel${NC}"
  NEED_FW_RELOAD=false
  for PORT in 8090 8443 80 443; do
    if check_port_open $PORT tcp; then
      log_ok "Port ${PORT}/tcp terbuka"
    else
      log_warn "Port ${PORT}/tcp tertutup"
      if [[ "$OS" == "almalinux" ]]; then
        firewall-cmd --permanent --add-port=${PORT}/tcp &>/dev/null
        NEED_FW_RELOAD=true
      else
        ufw allow ${PORT}/tcp &>/dev/null
      fi
      log_fixed "Port ${PORT}/tcp dibuka di firewall"
    fi
  done
  if [[ "$NEED_FW_RELOAD" == true ]]; then
    firewall-cmd --reload &>/dev/null
  fi

  # MySQL
  echo -e "\n  ${BOLD}🗄 Database${NC}"
  if systemctl is-active --quiet mysql 2>/dev/null || systemctl is-active --quiet mariadb 2>/dev/null; then
    log_ok "MySQL/MariaDB berjalan"
  else
    log_warn "MySQL/MariaDB mati"
    systemctl restart mysql 2>/dev/null || systemctl restart mariadb 2>/dev/null
    sleep 3
    if systemctl is-active --quiet mysql 2>/dev/null || systemctl is-active --quiet mariadb 2>/dev/null; then
      log_fixed "MySQL/MariaDB direstart"
    else
      log_manual "MySQL/MariaDB gagal start — cek: journalctl -u mysql -n 50"
    fi
  fi

  # LiteSpeed — FIX T9: Verifikasi restart
  echo -e "\n  ${BOLD}🌐 LiteSpeed Web Server${NC}"
  if systemctl is-active --quiet lsws 2>/dev/null; then
    log_ok "LiteSpeed berjalan"
  else
    log_warn "LiteSpeed mati"
    /usr/local/lsws/bin/lswsctrl restart &>/dev/null
    sleep 3
    if systemctl is-active --quiet lsws 2>/dev/null; then
      log_fixed "LiteSpeed direstart"
    else
      log_manual "LiteSpeed gagal restart — cek: /usr/local/lsws/logs/error.log"
    fi
  fi
fi

# ============================================================
# CEK MINECRAFT
# ============================================================
if [[ "$HAS_MINECRAFT" == true ]]; then
  section "FASE 2: CEK MINECRAFT SERVER"

  MC_DIR="/home/minecraft/server"
  PLUGIN_DIR="${MC_DIR}/plugins"

  # Status server
  echo -e "\n  ${BOLD}🎮 Minecraft Service${NC}"
  if systemctl is-active --quiet minecraft; then
    log_ok "Minecraft server berjalan"
  else
    log_warn "Minecraft server mati"
    systemctl restart minecraft &>/dev/null
    sleep 15
    if systemctl is-active --quiet minecraft; then
      log_fixed "Minecraft server direstart"
    else
      log_manual "Minecraft gagal start — cek: journalctl -u minecraft -n 50"
    fi
  fi

  # Java
  echo -e "\n  ${BOLD}☕ Java${NC}"
  if command -v java &>/dev/null; then
    JAVA_VER=$(java -version 2>&1 | head -1)
    log_ok "Java terinstall: ${JAVA_VER}"
  else
    log_warn "Java tidak terinstall"
    if [[ "$OS" == "almalinux" ]]; then
      dnf install -y -q java-21-openjdk &>/dev/null
    else
      apt install -y -qq openjdk-21-jdk &>/dev/null
    fi
    if command -v java &>/dev/null; then
      log_fixed "Java 21 berhasil diinstall"
    else
      log_manual "Gagal install Java — cek koneksi internet dan repo"
    fi
  fi

  # FIX T4 & T5: Port Minecraft — reload sekali, cek protokol eksplisit
  echo -e "\n  ${BOLD}🔌 Port Minecraft${NC}"
  NEED_FW_RELOAD=false

  if check_port_open 25565 tcp; then
    log_ok "Port 25565/tcp (Java) terbuka"
  else
    log_warn "Port 25565/tcp tertutup"
    if [[ "$OS" == "almalinux" ]]; then
      firewall-cmd --permanent --add-port=25565/tcp &>/dev/null
      NEED_FW_RELOAD=true
    else
      ufw allow 25565/tcp &>/dev/null
    fi
    log_fixed "Port 25565/tcp dibuka"
  fi

  if check_port_open 19132 udp; then
    log_ok "Port 19132/udp (Bedrock/Geyser) terbuka"
  else
    log_warn "Port 19132/udp tertutup"
    if [[ "$OS" == "almalinux" ]]; then
      firewall-cmd --permanent --add-port=19132/udp &>/dev/null
      NEED_FW_RELOAD=true
    else
      ufw allow 19132/udp &>/dev/null
    fi
    log_fixed "Port 19132/udp dibuka"
  fi

  if [[ "$NEED_FW_RELOAD" == true ]]; then
    firewall-cmd --reload &>/dev/null
  fi

  # Paper jar
  echo -e "\n  ${BOLD}📦 Paper Server${NC}"
  if [[ -f "${MC_DIR}/paper.jar" ]]; then
    PAPER_SIZE=$(du -sh "${MC_DIR}/paper.jar" | cut -f1)
    log_ok "paper.jar ada (${PAPER_SIZE})"
  else
    log_warn "paper.jar tidak ditemukan"
    PAPER_VERSION=$(curl -s --max-time 10 https://api.papermc.io/v2/projects/paper | jq -r '.versions[-1]' 2>/dev/null)
    PAPER_BUILD=$(curl -s --max-time 10 "https://api.papermc.io/v2/projects/paper/versions/${PAPER_VERSION}/builds" | jq -r '.builds[-1].build' 2>/dev/null)
    if [[ -n "$PAPER_VERSION" && "$PAPER_VERSION" != "null" ]]; then
      PAPER_JAR="paper-${PAPER_VERSION}-${PAPER_BUILD}.jar"
      PAPER_URL="https://api.papermc.io/v2/projects/paper/versions/${PAPER_VERSION}/builds/${PAPER_BUILD}/downloads/${PAPER_JAR}"
      wget -q -O "${MC_DIR}/paper.jar" "${PAPER_URL}" && log_fixed "paper.jar berhasil didownload ulang" || log_manual "Gagal download paper.jar"
    else
      log_manual "Gagal akses Paper API — cek koneksi internet"
    fi
  fi

  # FIX T15 & T16: Plugin check — hapus MISSING_COUNT yang tidak dipakai, tambah restart Minecraft setelah download
  echo -e "\n  ${BOLD}🔌 Plugin${NC}"
  declare -A PLUGINS=(
    ["EssentialsX.jar"]="EssentialsX/Essentials|EssentialsX-[0-9].*\.jar"
    ["LuckPerms.jar"]="LuckPerms/LuckPerms|LuckPerms-Bukkit.*\.jar"
    ["WorldEdit.jar"]="EngineHub/WorldEdit|worldedit-bukkit.*\.jar"
    ["WorldGuard.jar"]="EngineHub/WorldGuard|worldguard-bukkit.*\.jar"
    ["Geyser-Spigot.jar"]="GeyserMC/Geyser|Geyser-Spigot\.jar"
    ["Floodgate-Spigot.jar"]="GeyserMC/Floodgate|floodgate-spigot\.jar"
  )

  PLUGINS_DOWNLOADED=false
  for PLUGIN_FILE in "${!PLUGINS[@]}"; do
    if [[ -f "${PLUGIN_DIR}/${PLUGIN_FILE}" ]]; then
      log_ok "Plugin ${PLUGIN_FILE} ada"
    else
      log_warn "Plugin ${PLUGIN_FILE} tidak ditemukan"
      IFS='|' read -r REPO PATTERN <<< "${PLUGINS[$PLUGIN_FILE]}"
      ASSET_URL=$(curl -s --max-time 10 "https://api.github.com/repos/${REPO}/releases/latest" | \
        jq -r ".assets[] | select(.name | test(\"${PATTERN}\")) | .browser_download_url" 2>/dev/null | head -1)
      if [[ -n "$ASSET_URL" && "$ASSET_URL" != "null" ]]; then
        wget -q -O "${PLUGIN_DIR}/${PLUGIN_FILE}" "${ASSET_URL}" && \
          log_fixed "Plugin ${PLUGIN_FILE} didownload ulang" && PLUGINS_DOWNLOADED=true || \
          log_manual "Gagal download ${PLUGIN_FILE}"
      else
        log_manual "Gagal cari download URL untuk ${PLUGIN_FILE}"
      fi
    fi
  done

  # FIX T15: Restart Minecraft jika ada plugin yang didownload
  if [[ "$PLUGINS_DOWNLOADED" == true ]]; then
    log_info "Ada plugin baru didownload — merestart Minecraft..."
    systemctl restart minecraft &>/dev/null
    sleep 15
    if systemctl is-active --quiet minecraft; then
      log_fixed "Minecraft direstart setelah update plugin"
    else
      log_manual "Minecraft gagal restart setelah update plugin — cek manual"
    fi
  fi

  # Permission folder
  echo -e "\n  ${BOLD}🔑 Permission Folder${NC}"
  OWNER=$(stat -c '%U' ${MC_DIR} 2>/dev/null)
  if [[ "$OWNER" == "minecraft" ]]; then
    log_ok "Permission folder OK (owner: minecraft)"
  else
    log_warn "Permission folder salah (owner: ${OWNER})"
    chown -R minecraft:minecraft /home/minecraft/
    log_fixed "Permission folder diperbaiki"
  fi

  # EULA
  echo -e "\n  ${BOLD}📋 EULA${NC}"
  if [[ -f "${MC_DIR}/eula.txt" ]] && grep -q "eula=true" "${MC_DIR}/eula.txt"; then
    log_ok "EULA sudah disetujui"
  else
    log_warn "EULA belum disetujui"
    echo "eula=true" > "${MC_DIR}/eula.txt"
    log_fixed "EULA disetujui otomatis"
  fi

  # Auto update cron
  echo -e "\n  ${BOLD}🔄 Auto Update Cron${NC}"
  if crontab -l 2>/dev/null | grep -q "auto_update.sh"; then
    log_ok "Cron auto update aktif"
  else
    log_warn "Cron auto update tidak ditemukan"
    if [[ -f "/home/minecraft/auto_update.sh" ]]; then
      (crontab -l 2>/dev/null; echo "0 4 * * * /home/minecraft/auto_update.sh >> /home/minecraft/logs/update.log 2>&1") | crontab -
      log_fixed "Cron auto update dipasang ulang"
    else
      log_manual "File auto_update.sh tidak ada — jalankan ulang minecraft_server.sh"
    fi
  fi
fi

# ============================================================
# FASE 3: CEK HARDENING & KEAMANAN
# ============================================================
if [[ "$HAS_HARDENING" == true ]] || [[ "$HAS_FAIL2BAN" == true ]]; then
  section "FASE 3: CEK HARDENING & KEAMANAN"

  # Fail2Ban
  echo -e "\n  ${BOLD}🚫 Fail2Ban${NC}"
  if [[ "$HAS_FAIL2BAN" == true ]]; then
    if systemctl is-active --quiet fail2ban; then
      log_ok "Fail2Ban berjalan"
      BANNED_COUNT=$(fail2ban-client status sshd 2>/dev/null | grep "Currently banned" | awk '{print $NF}')
      log_info "IP currently banned: ${BANNED_COUNT:-0}"
    else
      log_warn "Fail2Ban mati"
      systemctl enable fail2ban --now &>/dev/null
      sleep 3
      if systemctl is-active --quiet fail2ban; then
        log_fixed "Fail2Ban direstart"
      else
        log_manual "Fail2Ban gagal start — cek: journalctl -u fail2ban -n 50"
      fi
    fi
  fi

  # Firewall — FIX T11: Pastikan SSH port terbuka SEBELUM enable UFW
  echo -e "\n  ${BOLD}🛡 Firewall${NC}"
  if [[ "$OS" == "almalinux" ]]; then
    if systemctl is-active --quiet firewalld; then
      log_ok "Firewalld berjalan"
    else
      log_warn "Firewalld mati"
      # FIX T11: Tambah SSH port dulu sebelum enable
      systemctl enable firewalld --now &>/dev/null
      sleep 2
      CURRENT_SSH_PORT=$(grep "^Port " /etc/ssh/sshd_config 2>/dev/null | awk '{print $2}' || echo "22")
      firewall-cmd --permanent --add-port=${CURRENT_SSH_PORT}/tcp &>/dev/null
      firewall-cmd --reload &>/dev/null
      if systemctl is-active --quiet firewalld; then
        log_fixed "Firewalld diaktifkan kembali"
      else
        log_manual "Firewalld gagal start — cek: journalctl -u firewalld -n 50"
      fi
    fi
  else
    if ufw status 2>/dev/null | grep -q "Status: active"; then
      log_ok "UFW aktif"
    else
      log_warn "UFW tidak aktif"
      # FIX T11: Pastikan SSH port terbuka SEBELUM enable
      CURRENT_SSH_PORT=$(grep "^Port " /etc/ssh/sshd_config 2>/dev/null | awk '{print $2}' || echo "22")
      ufw allow ${CURRENT_SSH_PORT}/tcp &>/dev/null
      ufw --force enable &>/dev/null
      if ufw status 2>/dev/null | grep -q "Status: active"; then
        log_fixed "UFW diaktifkan (port SSH ${CURRENT_SSH_PORT} dipastikan terbuka)"
      else
        log_manual "UFW gagal aktif — cek manual"
      fi
    fi
  fi

  # SSH Config — FIX T1: MaxAuthTries tidak dobel
  echo -e "\n  ${BOLD}🔐 SSH${NC}"
  SSH_PORT_CURRENT=$(grep "^Port" /etc/ssh/sshd_config 2>/dev/null | awk '{print $2}')
  if [[ -n "$SSH_PORT_CURRENT" && "$SSH_PORT_CURRENT" != "22" ]]; then
    log_ok "SSH port custom: ${SSH_PORT_CURRENT}"
  else
    log_info "SSH masih pakai port 22 — pertimbangkan ganti port via hardening.sh"
  fi

  MAX_AUTH=$(grep "^MaxAuthTries" /etc/ssh/sshd_config 2>/dev/null | awk '{print $2}')
  if [[ -n "$MAX_AUTH" && "$MAX_AUTH" -le 3 ]]; then
    log_ok "MaxAuthTries SSH: ${MAX_AUTH}"
  else
    log_warn "MaxAuthTries SSH tidak dikonfigurasi"
    # FIX T1: Hapus dulu semua baris MaxAuthTries, baru tambah 1
    sed -i '/^#\?MaxAuthTries/d' /etc/ssh/sshd_config
    echo "MaxAuthTries 3" >> /etc/ssh/sshd_config
    if sshd -t 2>/dev/null; then
      systemctl restart sshd &>/dev/null
      log_fixed "MaxAuthTries diset ke 3"
    else
      log_manual "SSH config error setelah set MaxAuthTries — cek: sshd -t"
    fi
  fi

  # Sysctl hardening
  echo -e "\n  ${BOLD}⚙️  Sysctl${NC}"
  if [[ -f "/etc/sysctl.d/99-hardening-ikyy.conf" ]]; then
    log_ok "Sysctl hardening aktif"
  else
    log_warn "Sysctl hardening tidak ditemukan"
    cat > /etc/sysctl.d/99-hardening-ikyy.conf <<SYSCTL
net.ipv4.conf.all.rp_filter = 1
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.tcp_syncookies = 1
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
SYSCTL
    sysctl -p /etc/sysctl.d/99-hardening-ikyy.conf &>/dev/null
    log_fixed "Sysctl hardening dipasang ulang"
  fi

  # FIX T10: Cek ikyy_monitor dan ikyy_bot
  echo -e "\n  ${BOLD}🛡 IKYY Monitor${NC}"
  if [[ -f "/opt/ikyy_monitor/monitor.sh" ]]; then
    if systemctl is-active --quiet ikyy_monitor; then
      log_ok "ikyy_monitor service berjalan"
    else
      log_warn "ikyy_monitor service mati"
      systemctl enable ikyy_monitor --now &>/dev/null
      sleep 3
      if systemctl is-active --quiet ikyy_monitor; then
        log_fixed "ikyy_monitor direstart"
      else
        log_manual "ikyy_monitor gagal start — cek: journalctl -u ikyy_monitor -n 50"
      fi
    fi

    if systemctl is-active --quiet ikyy_bot; then
      log_ok "ikyy_bot service berjalan"
    else
      log_warn "ikyy_bot service mati"
      systemctl enable ikyy_bot --now &>/dev/null
      sleep 3
      if systemctl is-active --quiet ikyy_bot; then
        log_fixed "ikyy_bot direstart"
      else
        log_manual "ikyy_bot gagal start — cek: journalctl -u ikyy_bot -n 50"
      fi
    fi
  else
    log_info "IKYY Monitor belum terinstall — jalankan monitoring.sh untuk install"
  fi
fi

# ============================================================
# FASE 3: CEK PORT HTTP/HTTPS UMUM
# ============================================================
section "FASE 3: CEK PORT UMUM"

echo -e "\n  ${BOLD}🌐 Port Web Dasar${NC}"
NEED_FW_RELOAD=false
for PORT in 80 443; do
  # FIX T5: Cek port dengan protokol eksplisit
  if check_port_open $PORT tcp; then
    log_ok "Port ${PORT}/tcp terbuka"
  else
    log_warn "Port ${PORT}/tcp tertutup"
    if [[ "$OS" == "almalinux" ]]; then
      firewall-cmd --permanent --add-port=${PORT}/tcp &>/dev/null
      NEED_FW_RELOAD=true
    else
      ufw allow ${PORT}/tcp &>/dev/null
    fi
    log_fixed "Port ${PORT}/tcp dibuka"
  fi
done
if [[ "$NEED_FW_RELOAD" == true ]]; then
  firewall-cmd --reload &>/dev/null
fi

# ============================================================
# FASE 4: LAPORAN AKHIR
# FIX T7: Fase dinomori dengan benar (bukan loncat ke Fase 4)
# ============================================================
section "FASE 4: LAPORAN HASIL"

echo ""
echo -e "${CYAN}${BOLD}"
echo "  ================================================================"
echo "   TROUBLESHOOT SELESAI — LAPORAN HASIL"
echo "  ================================================================"
echo -e "${NC}"

# FIX T12 & T13: Counter sekarang konsisten
echo -e "  🔍 Total masalah ditemukan : ${YELLOW}${TOTAL_ISSUES}${NC}"
echo -e "  🔧 Berhasil auto-fix       : ${GREEN}${FIXED_ISSUES}${NC}"
echo -e "  ❌ Perlu tindakan manual   : ${RED}${MANUAL_ISSUES}${NC}"
echo ""

if [[ $TOTAL_ISSUES -eq 0 ]]; then
  echo -e "  ${GREEN}${BOLD}✅ Server lo sehat! Tidak ada masalah ditemukan.${NC}"
elif [[ $MANUAL_ISSUES -eq 0 ]]; then
  echo -e "  ${GREEN}${BOLD}✅ Semua masalah berhasil diperbaiki otomatis!${NC}"
else
  echo -e "  ${YELLOW}${BOLD}⚠️  Ada ${MANUAL_ISSUES} masalah yang perlu ditangani manual.${NC}"
  echo -e "  ${YELLOW}  Cek laporan lengkap di: ${CYAN}${REPORT_FILE}${NC}"
fi

# Kirim ringkasan ke Telegram
_notify_telegram "📋 <b>TROUBLESHOOT SELESAI</b>

🖥 Server: $(hostname)
⏰ $(date '+%Y-%m-%d %H:%M:%S')

🔍 Total masalah : ${TOTAL_ISSUES}
🔧 Auto-fixed    : ${FIXED_ISSUES}
❌ Manual needed : ${MANUAL_ISSUES}

$([ $TOTAL_ISSUES -eq 0 ] && echo '✅ Server sehat!' || echo "📋 Cek log: ${REPORT_FILE}")"

echo ""
echo -e "  📋 Log troubleshoot : ${CYAN}/var/log/troubleshoot_ikyy.log${NC}"
echo -e "  📋 Laporan detail   : ${CYAN}${REPORT_FILE}${NC}"
echo -e "${CYAN}  ================================================================${NC}"
echo ""
echo "=== Troubleshoot selesai: $(date) ===" >> $LOG_FILE

# --- FUNGSI CHECK PORT DENGAN PROTOKOL EKSPLISIT ---
# FIX T5: Override fungsi check_port_open dengan protokol eksplisit
check_port_open() {
  local PORT=$1
  local PROTO=${2:-tcp}
  if [[ "$OS" == "almalinux" ]]; then
    firewall-cmd --list-ports 2>/dev/null | grep -q "${PORT}/${PROTO}"
  else
    ufw status 2>/dev/null | grep -q "${PORT}/${PROTO}"
  fi
}
