#!/bin/bash

# Prevent interactive prompts
export DEBIAN_FRONTEND=noninteractive

# Prevent kernel restart prompt
echo '* libraries/restart-without-asking boolean true' | sudo debconf-set-selections

# Get Gabriel's password from Terraform argument
GABRIEL_PASSWORD=$1

# Create a 2GB swap file
if [ ! -f /swapfile ]; then
    echo "Creating swap file..."
    sudo fallocate -l 2G /swapfile
    sudo chmod 600 /swapfile
    sudo mkswap /swapfile
    sudo swapon /swapfile
    echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
else
    echo "Swap file already exists, skipping..."
fi

# Create a new user 'gabriel' with the generated password
if id "gabriel" &>/dev/null; then
    echo "User 'gabriel' already exists, skipping..."
else
    echo "Creating user 'gabriel'..."
    sudo useradd -m -s /bin/bash gabriel
    echo "gabriel:$GABRIEL_PASSWORD" | sudo chpasswd
    sudo usermod -aG ssl-cert gabriel
fi

# Update system & keep local SSH config
echo "Updating and upgrading system..."
sudo apt update -y
sudo apt-get -o Dpkg::Options::="--force-confold" --assume-yes upgrade

# Install XFCE4 (No Display Manager Needed)
echo "Installing XFCE4..."
sudo apt install -y xfce4 xfce4-goodies --no-install-recommends

# Install X2Go Server
echo "Installing X2Go Server..."
sudo apt install -y x2goserver x2goserver-xsession

# Install Chromium browser
echo "Installing Chromium..."
sudo apt install -y chromium-browser

# Set XFCE4 as the default session for X2Go
echo "xfce4-session" | sudo tee /home/gabriel/.xsession
sudo chown gabriel:gabriel /home/gabriel/.xsession

# Restart X2Go server
echo "Restarting X2Go Server..."
sudo systemctl restart x2goserver

# Store the password securely for reference
PASSWORD_FILE="/home/gabriel/.password.txt"
echo "$GABRIEL_PASSWORD" | sudo tee "$PASSWORD_FILE"
sudo chown gabriel:gabriel "$PASSWORD_FILE"
sudo chmod 600 "$PASSWORD_FILE"

echo "Setup completed successfully! Gabriel's password is stored securely."