#!/bin/bash

# ============================================================
#   VPS HARDENING - Auto Security Script
#   OS      : AlmaLinux 9 / Ubuntu 22 / Ubuntu 24
#   Author  : IKYY x CLAUDE
#   Version : 2.0 (Fixed)
#   Cocok   : WHM/cPanel, CyberPanel, atau VPS tanpa panel
# ============================================================

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

# --- BANNER ---
clear
echo -e "${CYAN}${BOLD}"
echo "  ██╗██╗  ██╗██╗   ██╗██╗   ██╗    ██╗  ██╗     ██╗  ██╗ █████╗ ██████╗ ██████╗ ███████╗███╗   ██╗"
echo "  ██║██║ ██╔╝╚██╗ ██╔╝╚██╗ ██╔╝    ╚██╗██╔╝     ██║  ██║██╔══██╗██╔══██╗██╔══██╗██╔════╝████╗  ██║"
echo "  ██║█████╔╝  ╚████╔╝  ╚████╔╝      ╚███╔╝      ███████║███████║██████╔╝██║  ██║█████╗  ██╔██╗ ██║"
echo "  ██║██╔═██╗   ╚██╔╝    ╚██╔╝       ██╔██╗      ██╔══██║██╔══██║██╔══██╗██║  ██║██╔══╝  ██║╚██╗██║"
echo "  ██║██║  ██╗   ██║      ██║       ██╔╝ ██╗     ██║  ██║██║  ██║██║  ██║██████╔╝███████╗██║ ╚████║"
echo "  ╚═╝╚═╝  ╚═╝   ╚═╝      ╚═╝       ╚═╝  ╚═╝     ╚═╝  ╚═╝╚═╝  ╚═╝╚═╝  ╚═╝╚═════╝ ╚══════╝╚═╝  ╚═══╝"
echo -e "${NC}"
echo -e "${YELLOW}  VPS Hardening Auto Script | Universal | 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}"
  echo -e "        Gunakan: sudo bash hardening.sh"
  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! Script ini hanya untuk AlmaLinux atau Ubuntu.${NC}"
  exit 1
fi

echo -e "${GREEN}[OK] OS Terdeteksi: ${OS_NAME}${NC}"
echo -e "${GREEN}[OK] Root check passed${NC}"
echo ""

# ============================================================
# INPUT KONFIGURASI
# ============================================================
echo -e "${CYAN}${BOLD}[ KONFIGURASI HARDENING ]${NC}"
echo ""

# FIX BUG 1: Validasi SSH port
while true; do
  read -p "  SSH Port baru (default: 2222, range: 1024-65535): " SSH_PORT
  SSH_PORT=${SSH_PORT:-2222}
  if [[ "$SSH_PORT" =~ ^[0-9]+$ ]] && [ "$SSH_PORT" -ge 1024 ] && [ "$SSH_PORT" -le 65535 ]; then
    break
  fi
  echo -e "  ${RED}Port tidak valid! Gunakan angka 1024-65535${NC}"
done

# FIX BUG 6: Tanya disable IPv6
read -p "  Disable IPv6? (y/n, default: n)                  : " DISABLE_IPV6
DISABLE_IPV6=${DISABLE_IPV6:-n}

read -p "  Buat user non-root? (y/n, default: n)            : " CREATE_USER
CREATE_USER=${CREATE_USER:-n}

if [[ "$CREATE_USER" == "y" || "$CREATE_USER" == "Y" ]]; then
  # FIX BUG 2: Validasi NEW_USER dan NEW_PASS tidak boleh kosong
  while [[ -z "$NEW_USER" ]]; do
    read -p "  Nama user baru                                    : " NEW_USER
  done
  while [[ -z "$NEW_PASS" ]]; do
    read -s -p "  Password user baru                                : " NEW_PASS
    echo ""
  done
fi

read -p "  Install Fail2Ban? (y/n, default: y)              : " INSTALL_F2B
INSTALL_F2B=${INSTALL_F2B:-y}

read -p "  Install ClamAV (antivirus)? (y/n, default: n)    : " INSTALL_AV
INSTALL_AV=${INSTALL_AV:-n}

read -p "  Aktifkan auto update otomatis? (y/n, default: y) : " AUTO_UPDATE
AUTO_UPDATE=${AUTO_UPDATE:-y}

# Deteksi panel
echo ""
echo -e "  Panel yang terinstall di server ini:"
echo -e "  ${YELLOW}1${NC} = WHM/cPanel"
echo -e "  ${YELLOW}2${NC} = CyberPanel"
echo -e "  ${YELLOW}3${NC} = Tidak ada panel (VPS kosong)"
read -p "  Pilih (1/2/3, default: 3)                         : " PANEL_TYPE
PANEL_TYPE=${PANEL_TYPE:-3}

echo ""
echo -e "${YELLOW}  ---- Konfigurasi yang akan diterapkan ----${NC}"
echo -e "  OS           : ${CYAN}${OS_NAME}${NC}"
echo -e "  SSH Port     : ${CYAN}${SSH_PORT}${NC}"
echo -e "  Disable IPv6 : ${CYAN}${DISABLE_IPV6}${NC}"
echo -e "  User baru    : ${CYAN}${CREATE_USER}${NC}"
echo -e "  Fail2Ban     : ${CYAN}${INSTALL_F2B}${NC}"
echo -e "  ClamAV       : ${CYAN}${INSTALL_AV}${NC}"
echo -e "  Auto Update  : ${CYAN}${AUTO_UPDATE}${NC}"
echo -e "  Panel        : ${CYAN}${PANEL_TYPE}${NC}"
echo ""
read -p "  Lanjutkan? (y/n): " CONFIRM
if [[ "$CONFIRM" != "y" && "$CONFIRM" != "Y" ]]; then
  echo -e "${RED}  Dibatalkan.${NC}"
  exit 0
fi
echo ""

# FIX BUG 3: Log dimulai SEBELUM step pertama
LOG_FILE="/var/log/hardening_ikyy.log"
exec > >(tee -a $LOG_FILE) 2>&1
echo "=== Hardening dimulai: $(date) ==="

# ============================================================
# STEP 1: UPDATE SISTEM
# ============================================================
echo -e "${CYAN}${BOLD}[STEP 1/9] Update sistem...${NC}"
if [[ "$OS" == "almalinux" ]]; then
  dnf update -y -q
  dnf install -y -q epel-release
else
  apt update -qq && apt upgrade -y -qq
fi
echo -e "${GREEN}  [OK] Sistem up-to-date${NC}"
echo ""

# ============================================================
# STEP 2: HARDENING SSH
# ============================================================
echo -e "${CYAN}${BOLD}[STEP 2/9] Hardening SSH...${NC}"

SSH_CONFIG="/etc/ssh/sshd_config"
cp $SSH_CONFIG ${SSH_CONFIG}.bak.$(date +%Y%m%d)

# FIX BUG 4: Ganti port dengan cara yang reliable (hapus dulu, tambah baru)
sed -i '/^#\?Port /d' $SSH_CONFIG
echo "Port $SSH_PORT" >> $SSH_CONFIG

# FIX BUG 5: Handle semua kemungkinan format PasswordAuthentication
sed -i 's/^#\?PermitRootLogin.*/PermitRootLogin yes/' $SSH_CONFIG
sed -i 's/^#\?PasswordAuthentication.*/PasswordAuthentication yes/' $SSH_CONFIG
sed -i 's/^X11Forwarding yes/X11Forwarding no/' $SSH_CONFIG
sed -i 's/^#\?MaxAuthTries.*/MaxAuthTries 3/' $SSH_CONFIG

# Tambah konfigurasi keamanan (FIX BUG 7: hapus Protocol 2 yang deprecated)
grep -q "LoginGraceTime" $SSH_CONFIG || cat >> $SSH_CONFIG <<EOF

# === Hardening IKYY x CLAUDE ===
LoginGraceTime 30
ClientAliveInterval 300
ClientAliveCountMax 2
MaxSessions 3
IgnoreRhosts yes
HostbasedAuthentication no
PermitEmptyPasswords no
EOF

# FIX BUG 8: Validasi sshd config sebelum restart
if ! sshd -t 2>/dev/null; then
  echo -e "${RED}  [ERROR] Config SSH tidak valid! Rollback...${NC}"
  cp ${SSH_CONFIG}.bak.$(date +%Y%m%d) $SSH_CONFIG
  exit 1
fi

# FIX BUG 9: SSH restart SETELAH firewall (dipindah ke bawah Step 3)
echo -e "${GREEN}  [OK] SSH config dikeraskan, port: ${SSH_PORT}${NC}"
echo ""

# ============================================================
# STEP 3: FIREWALL
# ============================================================
echo -e "${CYAN}${BOLD}[STEP 3/9] Setup Firewall...${NC}"

if [[ "$OS" == "almalinux" ]]; then
  dnf install -y -q firewalld
  systemctl enable firewalld --now

  # FIX BUG 10: --permanent untuk set-default-zone
  firewall-cmd --permanent --set-default-zone=drop

  # Allow SSH DULU sebelum apapun
  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=53/tcp
  firewall-cmd --permanent --add-port=53/udp

  if [[ "$PANEL_TYPE" == "1" ]]; then
    firewall-cmd --permanent --add-port=21/tcp
    firewall-cmd --permanent --add-port=25/tcp
    firewall-cmd --permanent --add-port=110/tcp
    firewall-cmd --permanent --add-port=143/tcp
    firewall-cmd --permanent --add-port=465/tcp
    firewall-cmd --permanent --add-port=587/tcp
    firewall-cmd --permanent --add-port=993/tcp
    firewall-cmd --permanent --add-port=995/tcp
    firewall-cmd --permanent --add-port=2082/tcp
    firewall-cmd --permanent --add-port=2083/tcp
    firewall-cmd --permanent --add-port=2086/tcp
    firewall-cmd --permanent --add-port=2087/tcp
    firewall-cmd --permanent --add-port=2095/tcp
    firewall-cmd --permanent --add-port=2096/tcp
    echo -e "${GREEN}  [OK] Port WHM/cPanel dibuka${NC}"
  elif [[ "$PANEL_TYPE" == "2" ]]; then
    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=25/tcp
    firewall-cmd --permanent --add-port=110/tcp
    firewall-cmd --permanent --add-port=143/tcp
    firewall-cmd --permanent --add-port=465/tcp
    firewall-cmd --permanent --add-port=587/tcp
    firewall-cmd --permanent --add-port=993/tcp
    firewall-cmd --permanent --add-port=995/tcp
    echo -e "${GREEN}  [OK] Port CyberPanel dibuka${NC}"
  fi

  firewall-cmd --reload

else
  # Ubuntu - UFW
  apt install -y -qq ufw

  # FIX BUG 11: Allow SSH dulu SEBELUM enable
  ufw --force reset
  ufw default deny incoming
  ufw default allow outgoing
  ufw allow ${SSH_PORT}/tcp
  ufw allow 80/tcp
  ufw allow 443/tcp
  # FIX BUG 12: ufw allow 53 dengan protokol eksplisit
  ufw allow 53/tcp
  ufw allow 53/udp

  if [[ "$PANEL_TYPE" == "1" ]]; then
    ufw allow 21/tcp
    ufw allow 25/tcp
    ufw allow 110/tcp
    ufw allow 143/tcp
    ufw allow 465/tcp
    ufw allow 587/tcp
    ufw allow 993/tcp
    ufw allow 995/tcp
    ufw allow 2082/tcp
    ufw allow 2083/tcp
    ufw allow 2086/tcp
    ufw allow 2087/tcp
    ufw allow 2095/tcp
    ufw allow 2096/tcp
    echo -e "${GREEN}  [OK] Port WHM/cPanel dibuka${NC}"
  elif [[ "$PANEL_TYPE" == "2" ]]; then
    ufw allow 8090/tcp
    ufw allow 8443/tcp
    ufw allow 21/tcp
    ufw allow 25/tcp
    ufw allow 110/tcp
    ufw allow 143/tcp
    ufw allow 465/tcp
    ufw allow 587/tcp
    ufw allow 993/tcp
    ufw allow 995/tcp
    echo -e "${GREEN}  [OK] Port CyberPanel dibuka${NC}"
  fi

  ufw --force enable
fi

# FIX BUG 9: SSH restart SETELAH firewall selesai
if ! systemctl restart sshd 2>/dev/null && ! service ssh restart 2>/dev/null; then
  echo -e "${RED}  [ERROR] SSH gagal restart! Rollback config SSH...${NC}"
  cp ${SSH_CONFIG}.bak.$(date +%Y%m%d) $SSH_CONFIG
  systemctl restart sshd 2>/dev/null || service ssh restart 2>/dev/null
  exit 1
fi

echo -e "${GREEN}  [OK] Firewall aktif${NC}"
echo -e "${GREEN}  [OK] SSH restart sukses di port ${SSH_PORT}${NC}"
echo ""

# ============================================================
# STEP 4: FAIL2BAN
# ============================================================
if [[ "$INSTALL_F2B" == "y" || "$INSTALL_F2B" == "Y" ]]; then
  echo -e "${CYAN}${BOLD}[STEP 4/9] Install & Konfigurasi Fail2Ban...${NC}"

  if [[ "$OS" == "almalinux" ]]; then
    dnf install -y -q fail2ban
  else
    apt install -y -qq fail2ban
  fi

  # FIX BUG 13: Hapus [sshd-ddos] yang sudah deprecated di Fail2Ban modern
  # Ganti ke mode aggressive di [sshd]
  cat > /etc/fail2ban/jail.local <<EOF
[DEFAULT]
bantime  = 86400
findtime = 600
maxretry = 3
ignoreip = 127.0.0.1/8

[sshd]
enabled  = true
mode     = aggressive
port     = ${SSH_PORT}
logpath  = %(sshd_log)s
maxretry = 3
bantime  = 86400
EOF

  if [[ "$PANEL_TYPE" == "1" ]]; then
    cat >> /etc/fail2ban/jail.local <<EOF

[cpanel-login]
enabled  = true
port     = 2082,2083,2086,2087,2095,2096
logpath  = /usr/local/cpanel/logs/login_log
maxretry = 3
bantime  = 86400
EOF
  elif [[ "$PANEL_TYPE" == "2" ]]; then
    cat >> /etc/fail2ban/jail.local <<EOF

[cyberpanel-login]
enabled  = true
port     = 8090,8443
logpath  = /var/log/cyberpanel.log
maxretry = 3
bantime  = 86400
EOF
  fi

  systemctl enable fail2ban --now
  sleep 2
  if systemctl is-active --quiet fail2ban; then
    echo -e "${GREEN}  [OK] Fail2Ban aktif — auto ban setelah 3x gagal login${NC}"
  else
    echo -e "${RED}  [WARN] Fail2Ban gagal start — cek: journalctl -u fail2ban -n 20${NC}"
  fi
else
  echo -e "${YELLOW}  [SKIP] Fail2Ban dilewati${NC}"
fi
echo ""

# ============================================================
# STEP 5: BUAT USER NON-ROOT
# ============================================================
if [[ "$CREATE_USER" == "y" || "$CREATE_USER" == "Y" ]]; then
  echo -e "${CYAN}${BOLD}[STEP 5/9] Buat User Non-Root...${NC}"
  useradd -m -s /bin/bash "$NEW_USER" 2>/dev/null || true
  echo "$NEW_USER:$NEW_PASS" | chpasswd
  usermod -aG wheel "$NEW_USER" 2>/dev/null || usermod -aG sudo "$NEW_USER" 2>/dev/null
  echo -e "${GREEN}  [OK] User ${NEW_USER} dibuat dengan akses sudo${NC}"
else
  echo -e "${YELLOW}  [SKIP] Pembuatan user non-root dilewati${NC}"
fi
echo ""

# ============================================================
# STEP 6: HARDENING SISTEM
# ============================================================
echo -e "${CYAN}${BOLD}[STEP 6/9] Hardening Parameter Sistem...${NC}"

# FIX BUG 14: IPv6 hanya dimatikan kalau user setuju
SYSCTL_FILE="/etc/sysctl.d/99-hardening-ikyy.conf"
cat > $SYSCTL_FILE <<EOF
# === IKYY x CLAUDE — Sysctl Hardening ===

# Proteksi IP Spoofing
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1

# Ignore ICMP broadcast (Smurf attack)
net.ipv4.icmp_echo_ignore_broadcasts = 1

# Ignore bogus ICMP errors
net.ipv4.icmp_ignore_bogus_error_responses = 1

# Disable IP source routing
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0

# Disable ICMP redirect
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0

# Enable SYN cookies (proteksi SYN flood)
net.ipv4.tcp_syncookies = 1

# Log suspicious packets
net.ipv4.conf.all.log_martians = 1
EOF

if [[ "$DISABLE_IPV6" == "y" || "$DISABLE_IPV6" == "Y" ]]; then
  cat >> $SYSCTL_FILE <<EOF

# Disable IPv6
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
EOF
  echo -e "${GREEN}  [OK] IPv6 dinonaktifkan${NC}"
fi

sysctl -p $SYSCTL_FILE > /dev/null 2>&1
echo -e "${GREEN}  [OK] Parameter sistem dikeraskan${NC}"
echo ""

# ============================================================
# STEP 7: AUTO UPDATE
# ============================================================
if [[ "$AUTO_UPDATE" == "y" || "$AUTO_UPDATE" == "Y" ]]; then
  echo -e "${CYAN}${BOLD}[STEP 7/9] Setup Auto Update...${NC}"

  if [[ "$OS" == "almalinux" ]]; then
    dnf install -y -q dnf-automatic
    sed -i 's/^apply_updates = no/apply_updates = yes/' /etc/dnf/automatic.conf
    sed -i 's/^upgrade_type = default/upgrade_type = security/' /etc/dnf/automatic.conf
    # FIX BUG 15: Exclude kernel dari auto update agar tidak reboot sendiri
    grep -q "^exclude = kernel" /etc/dnf/automatic.conf || echo "exclude = kernel*" >> /etc/dnf/automatic.conf
    systemctl enable --now dnf-automatic.timer
  else
    apt install -y -qq unattended-upgrades
    dpkg-reconfigure -plow unattended-upgrades <<< "yes" > /dev/null 2>&1
  fi

  echo -e "${GREEN}  [OK] Auto security update aktif${NC}"
else
  echo -e "${YELLOW}  [SKIP] Auto update dilewati${NC}"
fi
echo ""

# ============================================================
# STEP 8: INSTALL CLAMAV (OPSIONAL)
# ============================================================
if [[ "$INSTALL_AV" == "y" || "$INSTALL_AV" == "Y" ]]; then
  echo -e "${CYAN}${BOLD}[STEP 8/9] Install ClamAV Antivirus...${NC}"

  if [[ "$OS" == "almalinux" ]]; then
    dnf install -y -q clamav clamav-update clamd
    # FIX BUG 16: freshclam dengan error handling
    freshclam --no-warnings 2>/dev/null || echo -e "${YELLOW}  [WARN] freshclam akan update otomatis nanti${NC}"
    systemctl enable clamav-freshclam --now 2>/dev/null || true
  else
    apt install -y -qq clamav clamav-daemon
    systemctl stop clamav-freshclam 2>/dev/null || true
    freshclam --no-warnings 2>/dev/null || echo -e "${YELLOW}  [WARN] freshclam akan update otomatis nanti${NC}"
    systemctl start clamav-freshclam 2>/dev/null || true
  fi

  cat > /etc/cron.weekly/clamav-scan <<'CRONEOF'
#!/bin/bash
clamscan -r /home /var/www /public_html --log=/var/log/clamav-weekly.log --quiet
CRONEOF
  chmod +x /etc/cron.weekly/clamav-scan

  echo -e "${GREEN}  [OK] ClamAV terinstall, scan mingguan dijadwalkan${NC}"
else
  echo -e "${YELLOW}  [SKIP] ClamAV dilewati${NC}"
fi
echo ""

# ============================================================
# STEP 9: PROTEKSI TAMBAHAN
# ============================================================
echo -e "${CYAN}${BOLD}[STEP 9/9] Proteksi Tambahan...${NC}"

# FIX BUG 17: Banner — hapus Protocol 2 dari config, fix banner conflict
echo "" > /etc/issue
echo "" > /etc/issue.net
# Hapus semua baris Banner dulu, tambah yang benar
sed -i '/^#\?Banner/d' /etc/ssh/sshd_config
echo "Banner none" >> /etc/ssh/sshd_config

# Disable USB storage
cat > /etc/modprobe.d/disable-usb.conf <<EOF
install usb-storage /bin/true
EOF

# FIX BUG 18: /tmp remount — tambah warning perlu reboot
if ! grep -q "tmpfs /tmp" /etc/fstab; then
  echo "tmpfs /tmp tmpfs defaults,noexec,nosuid,nodev 0 0" >> /etc/fstab
  echo -e "${YELLOW}  [INFO] /tmp hardening aktif setelah reboot${NC}"
fi

# Proteksi file konfigurasi penting
chmod 600 /etc/ssh/sshd_config
chmod 600 /etc/crontab 2>/dev/null || true

# Hapus package tidak perlu
if [[ "$OS" == "almalinux" ]]; then
  dnf remove -y -q telnet rsh rlogin 2>/dev/null || true
else
  apt remove -y -qq telnet rsh-client 2>/dev/null || true
fi

# Validasi SSH config final sebelum restart terakhir
if sshd -t 2>/dev/null; then
  systemctl restart sshd 2>/dev/null || service ssh restart 2>/dev/null
  echo -e "${GREEN}  [OK] Proteksi tambahan diterapkan${NC}"
else
  echo -e "${RED}  [WARN] SSH config ada masalah, skip restart terakhir${NC}"
fi
echo ""

# ============================================================
# HEALTH CHECK
# ============================================================
echo -e "${CYAN}${BOLD}[ HEALTH CHECK ]${NC}"
echo ""

# Cek SSH
if systemctl is-active --quiet sshd 2>/dev/null || systemctl is-active --quiet ssh 2>/dev/null; then
  echo -e "  SSH              : ${GREEN}✅ Aktif${NC} (port ${SSH_PORT})"
else
  echo -e "  SSH              : ${RED}❌ MATI — cek manual!${NC}"
fi

# Cek Firewall
if [[ "$OS" == "almalinux" ]]; then
  if systemctl is-active --quiet firewalld; then
    echo -e "  Firewall         : ${GREEN}✅ Aktif${NC}"
  else
    echo -e "  Firewall         : ${RED}❌ MATI${NC}"
  fi
else
  if ufw status 2>/dev/null | grep -q "Status: active"; then
    echo -e "  Firewall         : ${GREEN}✅ Aktif${NC}"
  else
    echo -e "  Firewall         : ${RED}❌ MATI${NC}"
  fi
fi

# Cek Fail2Ban
if [[ "$INSTALL_F2B" == "y" || "$INSTALL_F2B" == "Y" ]]; then
  if systemctl is-active --quiet fail2ban; then
    echo -e "  Fail2Ban         : ${GREEN}✅ Aktif${NC}"
  else
    echo -e "  Fail2Ban         : ${RED}❌ MATI — cek: journalctl -u fail2ban -n 20${NC}"
  fi
fi

# Cek Sysctl
if [[ -f "/etc/sysctl.d/99-hardening-ikyy.conf" ]]; then
  echo -e "  Sysctl Hardening : ${GREEN}✅ Aktif${NC}"
else
  echo -e "  Sysctl Hardening : ${RED}❌ Tidak ditemukan${NC}"
fi

echo ""

# ============================================================
# RINGKASAN HASIL
# ============================================================
echo -e "${CYAN}${BOLD}"
echo "  ================================================================"
echo "   HARDENING SELESAI! ALHAMDULILLAH — SERVER LO SUDAH LEBIH AMAN"
echo "  ================================================================"
echo -e "${NC}"

echo -e "${BOLD}  RINGKASAN YANG SUDAH DIAMANKAN:${NC}"
echo ""
echo -e "  🔐 SSH               : Port ${CYAN}${SSH_PORT}${NC} | MaxAuthTries 3"
echo -e "  🛡  Firewall          : ${CYAN}Aktif${NC} — hanya port yang diperlukan terbuka"
if [[ "$INSTALL_F2B" == "y" || "$INSTALL_F2B" == "Y" ]]; then
  echo -e "  🚫 Fail2Ban          : ${CYAN}Aktif${NC} — auto ban 24 jam setelah 3x gagal login"
fi
if [[ "$CREATE_USER" == "y" || "$CREATE_USER" == "Y" ]]; then
  echo -e "  👤 User Non-Root     : ${CYAN}${NEW_USER}${NC} sudah dibuat"
fi
if [[ "$AUTO_UPDATE" == "y" || "$AUTO_UPDATE" == "Y" ]]; then
  echo -e "  🔄 Auto Update       : ${CYAN}Aktif${NC} — patch keamanan otomatis (exclude kernel)"
fi
if [[ "$INSTALL_AV" == "y" || "$INSTALL_AV" == "Y" ]]; then
  echo -e "  🦠 ClamAV            : ${CYAN}Aktif${NC} — scan mingguan terjadwal"
fi
echo -e "  ⚙️  Sysctl            : ${CYAN}Aktif${NC} — proteksi SYN flood, IP spoofing, ICMP"
echo -e "  🔒 Proteksi Tambahan : ${CYAN}Aktif${NC} — banner tersembunyi, file permission"
if [[ "$DISABLE_IPV6" == "y" || "$DISABLE_IPV6" == "Y" ]]; then
  echo -e "  🌐 IPv6              : ${CYAN}Dinonaktifkan${NC}"
fi
echo ""
echo -e "${YELLOW}  ⚠ PENTING — CATAT INI:${NC}"
echo -e "  SSH Port baru : ${RED}${SSH_PORT}${NC}"
echo -e "  Login SSH     : ${CYAN}ssh root@IP_SERVER -p ${SSH_PORT}${NC}"
echo ""
if [[ "$PANEL_TYPE" == "1" ]]; then
  echo -e "  WHM           : ${CYAN}https://IP_SERVER:2087${NC}"
  echo -e "  cPanel        : ${CYAN}https://IP_SERVER:2083${NC}"
elif [[ "$PANEL_TYPE" == "2" ]]; then
  echo -e "  CyberPanel    : ${CYAN}https://IP_SERVER:8090${NC}"
fi
echo ""
echo -e "  📋 Log hardening: ${CYAN}/var/log/hardening_ikyy.log${NC}"
echo -e "  📋 Cek IP banned: ${CYAN}fail2ban-client status sshd${NC}"
echo -e "${YELLOW}  ⚠ /tmp hardening aktif setelah reboot berikutnya${NC}"
echo -e "${CYAN}  ================================================================${NC}"
echo ""
