#!/bin/bash

# Phát hiện bản phân phối Linux
DISTRO=$(grep -E "^NAME" /etc/os-release | cut -d= -f2 | tr -d '"')

# Thư mục backup
BACKUP_DIR="/var/backups/config_backup_$(date +%Y%m%d%H%M%S)"
ROLLBACK_SCRIPT="$BACKUP_DIR/rollback.sh"

# Hàm tạo backup
backup_configs() {
    echo "Creating backup of current configurations..."
    mkdir -p "$BACKUP_DIR"

    # Backup sysctl
    sysctl -a > "$BACKUP_DIR/sysctl_backup.txt"
    cp /etc/sysctl.conf "$BACKUP_DIR/sysctl.conf" 2>/dev/null || true
    cp -r /etc/sysctl.d "$BACKUP_DIR/sysctl.d" 2>/dev/null || true

    # Backup ulimit (limits.conf và systemd nếu cần)
    cp /etc/security/limits.conf "$BACKUP_DIR/limits.conf" 2>/dev/null || true
    cp /etc/systemd/system.conf "$BACKUP_DIR/system.conf" 2>/dev/null || true
    cp /etc/systemd/user.conf "$BACKUP_DIR/user.conf" 2>/dev/null || true

    # Backup kernel modules
    lsmod > "$BACKUP_DIR/kernel_modules_backup.txt"

    echo "#!/bin/bash" > "$ROLLBACK_SCRIPT"
    echo "echo 'Rolling back configurations...'" >> "$ROLLBACK_SCRIPT"
    echo "cp '$BACKUP_DIR/sysctl.conf' /etc/sysctl.conf 2>/dev/null || true" >> "$ROLLBACK_SCRIPT"
    echo "cp -r '$BACKUP_DIR/sysctl.d' /etc/sysctl.d 2>/dev/null || true" >> "$ROLLBACK_SCRIPT"
    echo "cp '$BACKUP_DIR/limits.conf' /etc/security/limits.conf 2>/dev/null || true" >> "$ROLLBACK_SCRIPT"
    echo "cp '$BACKUP_DIR/system.conf' /etc/systemd/system.conf 2>/dev/null || true" >> "$ROLLBACK_SCRIPT"
    echo "cp '$BACKUP_DIR/user.conf' /etc/systemd/user.conf 2>/dev/null || true" >> "$ROLLBACK_SCRIPT"
    echo "echo 'Rollback completed!'" >> "$ROLLBACK_SCRIPT"
    chmod +x "$ROLLBACK_SCRIPT"

    echo "Backup completed: $BACKUP_DIR"
}

# Hàm rollback
rollback_configs() {
    if [ -f "$ROLLBACK_SCRIPT" ]; then
        echo "Rolling back configurations..."
        bash "$ROLLBACK_SCRIPT"
    else
        echo "No rollback script found!"
    fi
}

# Hàm áp dụng sysctl configurations
apply_sysctl() {
    echo "Applying sysctl configurations..."
    cat <<EOF | while IFS= read -r line; do
fs.file-max = 3214248
fs.nr_open = 1048576
net.core.somaxconn = 2048
net.core.netdev_max_backlog = 5000
net.ipv4.tcp_max_syn_backlog = 4096
net.ipv4.ip_local_port_range = 1024 65535
net.ipv4.tcp_fin_timeout = 15
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_rmem = 4096 87380 6291456
net.ipv4.tcp_wmem = 4096 16384 4194304
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_keepalive_intvl = 60
net.ipv4.tcp_keepalive_probes = 10
EOF
        if [[ "$line" =~ ^[^#]*= ]]; then
            key=$(echo "$line" | cut -d '=' -f 1 | xargs)
            value=$(echo "$line" | cut -d '=' -f 2- | xargs)
            sysctl -w "$key=$value"
        fi
    done
    sysctl -p
    echo "Sysctl configurations applied successfully."
}

# Hàm áp dụng ulimit configurations
apply_ulimit() {
    echo "Applying ulimit configurations..."

    ulimit -c 0                    # Core file size (blocks)
    ulimit -d unlimited             # Data segment size (kbytes)
    ulimit -f unlimited             # File size (blocks)
    ulimit -n 65536                 # Open files
    ulimit -s 8192                  # Stack size (kbytes)
    ulimit -u 65536                 # Max user processes
    ulimit -v unlimited             # Virtual memory (kbytes)

    echo "Ulimit configurations applied successfully."
}

# Hàm nạp kernel modules
#load_kernel_modules() {
#    echo "Loading kernel modules..."
#    cat <<EOF | while IFS= read -r module; do
#binfmt_misc
#iptable_filter
#xt_nat
#iptable_nat
#nf_conntrack_ipv4
#nf_defrag_ipv4
#nf_nat_ipv4
#nf_nat
#nf_conntrack
#libcrc32c
#vfat
#fat
#nvme
#bridge
#tun
#ip6table_filter
#xt_tcpudp
#nf_conntrack_ipv6
#nf_defrag_ipv6
#overlay
#fuse
#nfs
#nfsd
#lockd
#auth_rpcgss
#sunrpc
#iscsi_tcp
#e1000e
#xfs
#btrfs
#ext4
#mdio
#sata_sil
#sata_nv
#ahci
#irqbypass
#EOF
#        if [[ "$module" != "" && "$module" != "#"* ]]; then
#            modprobe "$module"
#        fi
#    done
#    echo "Kernel modules loaded successfully."
#}

# Tối ưu riêng cho CentOS
apply_centos_specific() {
    echo "Applying CentOS-specific optimizations..."
    
    # Ensure limits.conf settings are applied for CentOS
    echo "* soft nofile 65536" >> /etc/security/limits.conf
    echo "* hard nofile 65536" >> /etc/security/limits.conf
    echo "* soft nproc 65536" >> /etc/security/limits.conf
    echo "* hard nproc 65536" >> /etc/security/limits.conf
    
    # Ensure pam_limits is enabled (if not already)
    if ! grep -q "pam_limits.so" /etc/pam.d/common-session; then
        echo "session required pam_limits.so" >> /etc/pam.d/common-session
    fi

    # Apply systemd-related optimizations
    echo "DefaultLimitNOFILE=65536" >> /etc/systemd/system.conf
    echo "DefaultLimitNPROC=65536" >> /etc/systemd/system.conf
    systemctl daemon-reexec

    echo "CentOS-specific optimizations applied."
}

# Tối ưu riêng cho Ubuntu
apply_ubuntu_specific() {
    echo "Applying Ubuntu-specific optimizations..."
    echo "* soft nofile 65536" >> /etc/security/limits.conf
    echo "* hard nofile 65536" >> /etc/security/limits.conf
    echo "* soft nproc 65536" >> /etc/security/limits.conf
    echo "* hard nproc 65536" >> /etc/security/limits.conf
    echo "session required pam_limits.so" >> /etc/pam.d/common-session
    echo "session required pam_limits.so" >> /etc/pam.d/common-session-noninteractive
    echo "Ubuntu-specific optimizations applied."
}

# Menu lựa chọn
echo "Choose an action:"
echo "1) Backup current configurations"
echo "2) Apply optimizations (will automatically backup)"
echo "3) Rollback to previous configurations"
echo "4) Exit"
read -p "Enter your choice [1-4]: " choice

case $choice in
    1)
        backup_configs
        ;;
    2)
        backup_configs
        case $DISTRO in
            *Ubuntu*)
                apply_sysctl
                apply_ulimit
                #load_kernel_modules
                apply_ubuntu_specific
                ;;
            *CentOS*|*RedHat*)
                apply_sysctl
                apply_ulimit
                #load_kernel_modules
                apply_centos_specific
                ;;
            *)
                echo "Unknown Linux distribution. Only Ubuntu and CentOS are supported."
                ;;
        esac
        ;;
    3)
        rollback_configs
        ;;
    4)
        echo "Exiting."
        ;;
    *)
        echo "Invalid choice. Exiting."
        ;;
esac

echo "Operation completed."

