#!/bin/bash

# Exit immediately if a command exits with a non-zero status
set -e

export DEBIAN_FRONTEND=noninteractive

# Helper function to read input interactively even when script is executed via curl pipe
prompt_read() {
    local prompt_text="$1"
    local var_name="$2"
    if [ -t 0 ]; then
        read -r -p "$prompt_text" "$var_name"
    elif [ -e /dev/tty ]; then
        read -r -p "$prompt_text" "$var_name" < /dev/tty
    else
        read -r -p "$prompt_text" "$var_name"
    fi
}

echo "=== 1. Basic packages installation ==="
sudo DEBIAN_FRONTEND=noninteractive apt-get update -y
sudo DEBIAN_FRONTEND=noninteractive apt-get install -y nano curl

echo -e "\n=== 2. Enabling swap of 4GB ==="
current_swap_mb=$(free -m | awk '/^Swap:/ {print $2}')
if [ -z "$current_swap_mb" ]; then
    current_swap_mb=0
fi

swapfile_size=0
if [ -f /swapfile ]; then
    swapfile_size=$(stat -c %s /swapfile 2>/dev/null || echo 0)
fi

target_swap_bytes=4294967296

if [ "$current_swap_mb" -ge 3900 ]; then
    echo "Swap of 4GB is already active (${current_swap_mb} MB total). Skipping swap setup."
elif [ -f /swapfile ] && [ "$swapfile_size" -eq "$target_swap_bytes" ]; then
    echo "/swapfile of 4GB already exists. Enabling swap..."
    sudo swapon /swapfile 2>/dev/null || true
    if ! grep -q '/swapfile swap swap defaults 0 0' /etc/fstab; then
        echo '/swapfile swap swap defaults 0 0' | sudo tee -a /etc/fstab
    fi
    echo "Swap enabled."
else
    echo "Configuring 4GB swap..."
    sudo swapoff -a || true
    sudo rm -f /swapfile
    sudo fallocate -l 4G /swapfile
    sudo chmod 600 /swapfile
    sudo mkswap /swapfile
    sudo swapon /swapfile
    if ! grep -q '/swapfile swap swap defaults 0 0' /etc/fstab; then
        echo '/swapfile swap swap defaults 0 0' | sudo tee -a /etc/fstab
    fi
    echo "4GB swap configured and enabled."
fi

echo -e "\n=== 3. Allow root ssh login and insert public key ==="
prompt_read "Please paste the public key to add for root ssh access: " pub_key

# Update sshd_config to allow root login and pubkey authentication
sudo sed -i 's/^#*PermitRootLogin.*/PermitRootLogin yes/' /etc/ssh/sshd_config
sudo sed -i 's/^#*PubkeyAuthentication.*/PubkeyAuthentication yes/' /etc/ssh/sshd_config

# Setup root's authorized_keys
sudo mkdir -p /root/.ssh
sudo chmod 700 /root/.ssh

# For oracle instances, comment out the first line if it exists and contains restrictions
if sudo test -f /root/.ssh/authorized_keys; then
    sudo sed -i '1s/^[^#]/#&/' /root/.ssh/authorized_keys
fi

# Append the provided public key
if [ -n "$pub_key" ]; then
    echo "$pub_key" | sudo tee -a /root/.ssh/authorized_keys > /dev/null
    sudo chmod 600 /root/.ssh/authorized_keys
fi

sudo service ssh restart
echo "SSH service restarted."

echo -e "\n=== 4. Basic ufw firewall setup ==="
prompt_read "Do you want to set up UFW firewall? (y/n): " setup_ufw
if [[ "$setup_ufw" =~ ^[Yy]$ ]]; then
    sudo DEBIAN_FRONTEND=noninteractive apt-get install -y ufw
    sudo ufw default deny incoming
    sudo ufw default allow outgoing
    sudo ufw allow 22/tcp
    sudo ufw allow 80/tcp
    
    prompt_read "Do you want to allow HTTPS (port 443)? (y/n): " allow_https
    if [[ "$allow_https" =~ ^[Yy]$ ]]; then
        sudo ufw allow 443/tcp
    fi
    
    sudo ufw --force enable
    sudo systemctl enable ufw
    sudo ufw status verbose
else
    echo "Skipping UFW setup."
fi

echo -e "\nSetup complete!"