#!/bin/bash

# -----------------------------------------
# Ubuntu 24 DataCenter Init Script
# -----------------------------------------

set -e

echo "========================================="
echo " Ubuntu 24 DataCenter Initialization Script"
echo "========================================="
echo
echo "Choose installation mode:"
echo " 1) Interactive mode (ask before each item)"
echo " 2) Install everything without asking"
read -rp "Enter number (1/2): " MODE

ASK() {
    if [ "$MODE" = "2" ]; then
        return 0
    fi
    read -rp "[Y/n] $1 ? " ans
    if [[ "$ans" =~ ^(Y|y| )*$ ]]; then
        return 0
    else
        return 1
    fi
}

# -----------------------------
# 1. System update
# -----------------------------
if ASK "Run system update (apt upgrade)"; then
    apt update && apt upgrade -y
fi

# -----------------------------
# 2. Install basic tools
# -----------------------------
tools=(
    vim htop curl wget git net-tools unzip rsync lsof tcpdump traceroute
    iperf3 chrony openssl jq nload iftop sysstat ncdu tmux
)
if ASK "Install basic utility packages"; then
    apt install -y "${tools[@]}"
fi

# -----------------------------
# 3. Set timezone + enable chrony
# -----------------------------
if ASK "Set timezone to Asia/Ho_Chi_Minh and enable chrony"; then
    timedatectl set-timezone Asia/Ho_Chi_Minh
    apt install -y chrony
    systemctl enable --now chronyd
fi

# -----------------------------
# 4. SSH hardening
# -----------------------------
if ASK "Apply SSH hardening"; then
    mkdir -p /etc/ssh/sshd_config.d
    cat > /etc/ssh/sshd_config.d/00-hardening.conf <<EOF
PasswordAuthentication no
PermitRootLogin prohibit-password
ClientAliveInterval 60
ClientAliveCountMax 3
UseDNS no
LoginGraceTime 30
EOF
    systemctl restart sshd
fi

# -----------------------------
# 5. sysctl tuning
# -----------------------------
if ASK "Apply recommended sysctl tuning"; then
    cat > /etc/sysctl.d/99-sysctl.conf <<EOF
fs.file-max = 1000000
net.core.somaxconn = 65535

net.ipv4.ip_forward = 1
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 10
net.ipv4.tcp_keepalive_time = 600

net.ipv4.ip_local_port_range = 1024 65535
EOF
    sysctl --system
fi

# -----------------------------
# 6. limits.conf tuning
# -----------------------------
if ASK "Set file descriptor limits in /etc/security/limits.conf"; then
    cat >> /etc/security/limits.conf <<EOF

* soft nofile 1000000
* hard nofile 1000000
EOF
fi

# -----------------------------
# 7. journald optimization
# -----------------------------
if ASK "Limit systemd-journal to max 2GB"; then
    mkdir -p /etc/systemd/journald.conf.d
    cat > /etc/systemd/journald.conf.d/size.conf <<EOF
[Journal]
Storage=persistent
SystemMaxUse=2G
EOF
    systemctl restart systemd-journald
fi

# -----------------------------
# 8. Disable Swap
# -----------------------------
if ASK "Disable swap"; then
    swapoff -a
    sed -i '/swap/d' /etc/fstab
fi

# -----------------------------
# 9. Disable cloud-init
# -----------------------------
if ASK "Disable cloud-init (recommended for bare metal / DC)"; then
    touch /etc/cloud/cloud-init.disabled
    systemctl disable --now cloud-init 2>/dev/null || true
fi

# -----------------------------
# 10. Install Prometheus node_exporter
# -----------------------------
if ASK "Install Prometheus node_exporter"; then
    useradd -r -s /usr/sbin/nologin node_exporter || true
    cd /tmp
    last=$(curl -s https://api.github.com/repos/prometheus/node_exporter/releases/latest | jq -r .tag_name)
    wget -q https://github.com/prometheus/node_exporter/releases/download/${last}/node_exporter-${last#v}.linux-amd64.tar.gz
    tar xf node_exporter-*.tar.gz
    cp node_exporter*/node_exporter /usr/local/bin/

    cat > /etc/systemd/system/node_exporter.service <<EOF
[Unit]
Description=Node Exporter
After=network.target

[Service]
User=node_exporter
ExecStart=/usr/local/bin/node_exporter
Restart=always

[Install]
WantedBy=default.target
EOF

    systemctl daemon-reload
    systemctl enable --now node_exporter
fi

# -----------------------------
# 11. Install fail2ban
# -----------------------------
if ASK "Install fail2ban"; then
    apt install -y fail2ban
    systemctl enable --now fail2ban
fi

# -----------------------------
# 12. Install Docker
# -----------------------------
if ASK "Install Docker"; then
    apt install -y ca-certificates curl gnupg
    install -m 0755 -d /etc/apt/keyrings

    curl -fsSL https://download.docker.com/linux/ubuntu/gpg \
        | gpg --dearmor -o /etc/apt/keyrings/docker.gpg

    echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] \
https://download.docker.com/linux/ubuntu noble stable" \
        > /etc/apt/sources.list.d/docker.list

    apt update
    apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
fi

# -----------------------------
# Finish
# -----------------------------
echo
echo "========================================="
echo " Initialization completed"
echo "========================================="
