#!/bin/bash

set -e

echo "========================================"
echo "[+] Fresh VPS Setup Script Started"
echo "========================================"

# Function to ask yes/no
confirm() {
    while true; do
        read -p "[?] $1 (y/n): " yn
        case $yn in
            [Yy]* ) return 0 ;;
            [Nn]* ) return 1 ;;
            * ) echo "[-] Please answer y or n." ;;
        esac
    done
}

# 1. Update and upgrade system
if confirm "Step 1: Run apt update && apt upgrade -y ?"; then
    echo "[+] Running system update and upgrade..."
    apt update && apt upgrade -y
    echo "[+] System updated successfully"
else
    echo "[-] Skipped system update"
fi

# 2. Install essential packages
if confirm "Step 2: Install essential packages (curl, wget, git, htop, bmon, unzip, neovim, net-tools, Python3 + pip + venv) ?"; then
    echo "[+] Installing essential packages..."
    apt install -y \
        curl wget git htop bmon unzip neovim net-tools \
        python3 python3-pip python3-venv
    echo "[+] Essential packages installed"
else
    echo "[-] Skipped package installation"
fi

# 3. Set timezone to Tehran
if confirm "Step 3: Set timezone to Asia/Tehran ?"; then
    echo "[+] Setting timezone to Asia/Tehran..."
    timedatectl set-timezone Asia/Tehran
    echo "[+] Timezone set to $(timedatectl show --property=Timezone --value)"
else
    echo "[-] Skipped timezone change"
fi

# 4. Install UFW and configure firewall
if confirm "Step 4: Install UFW and allow only SSH ?"; then
    echo "[+] Installing UFW..."
    apt install -y ufw
    ufw default deny incoming
    ufw default allow outgoing
    ufw allow ssh
    ufw --force enable
    echo "[+] UFW enabled with SSH allowed only"
else
    echo "[-] Skipped firewall setup"
fi

# 5. Install Fail2Ban
if confirm "Step 5: Install Fail2Ban ?"; then
    echo "[+] Installing Fail2Ban..."
    apt install -y fail2ban
    echo "[+] Fail2Ban installed"
else
    echo "[-] Skipped Fail2Ban installation"
fi

# 6 & 7. Hostname and /etc/hosts
if confirm "Step 6 & 7: Configure hostname and /etc/hosts ?"; then
    read -p "[?] Do you want to change the hostname? (y/n): " change_host
    if [[ "$change_host" =~ ^[Yy]$ ]]; then
        read -p "[?] Enter new hostname: " new_hostname
        if [ -n "$new_hostname" ]; then
            echo "$new_hostname" > /etc/hostname
            hostnamectl set-hostname "$new_hostname"
            echo "[+] Hostname changed to $new_hostname"
        fi
    fi

    echo "[+] Configuring /etc/hosts..."
    HOSTNAME=$(hostname)
    sed -i '/127.0.1.1/d' /etc/hosts 2>/dev/null || true
    echo "127.0.0.1   localhost" >> /etc/hosts
    echo "127.0.1.1   $HOSTNAME" >> /etc/hosts
    echo "[+] /etc/hosts configured"
else
    echo "[-] Skipped hostname configuration"
fi

# 8. Enable TCP BBR and network optimization
if confirm "Step 8: Enable TCP BBR and apply network optimizations ?"; then
    echo "[+] Applying TCP BBR and network optimizations..."
    cat << EOF >> /etc/sysctl.conf

# === Network Optimizations (added by VPS setup script) ===
net.core.default_qdisc = fq
net.ipv4.tcp_congestion_control = bbr
net.core.somaxconn = 4096
net.core.netdev_max_backlog = 4096
net.core.rmem_default = 10485760
net.core.rmem_max = 16777216
net.core.wmem_default = 10485760
net.core.wmem_max = 16777216
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216
net.ipv4.tcp_mtu_probing = 1
net.ipv4.tcp_fastopen = 3
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_timestamps = 0
net.ipv4.tcp_sack = 1
EOF

    sysctl -p > /dev/null
    echo "[+] TCP BBR enabled and network optimizations applied"
else
    echo "[-] Skipped network optimization"
fi

# 9 & 10. Cleanup
if confirm "Step 9 & 10: Run apt autoremove and apt clean ?"; then
    echo "[+] Cleaning up packages..."
    apt autoremove -y
    apt clean
    echo "[+] Cleanup completed"
else
    echo "[-] Skipped cleanup"
fi

# 11. Nginx installation (with check if already installed)
echo "[+] Step 11: Nginx setup"
if dpkg -l | grep -q nginx; then
    echo "[+] Nginx is already installed. Skipping installation."
else
    if confirm "Do you want to install Nginx ?"; then
        echo "[+] Installing Nginx..."
        apt install -y nginx
        
        echo "[+] Adding Nginx to UFW..."
        ufw allow 'Nginx Full'
        ufw reload
        
        echo "[+] Nginx installed and firewall rule added"
    else
        echo "[-] Nginx installation skipped"
    fi
fi

echo ""
echo "========================================"
echo "[+] VPS Setup Completed!"
echo "========================================"
echo "[+] Recommended: Reboot the server with 'reboot' for full effect."
echo "[+] You can check status with:"
echo "    timedatectl"
echo "    ufw status"
echo "    sysctl net.ipv4.tcp_congestion_control"
echo "    hostname"