#!/bin/bash
# Redirect all output to a log file in /root/
exec > /root/ut2004_setup.log 2>&1

# Path to the flag file
FLAG_FILE="/var/tmp/initial_setup_complete"

# Check if setup has already been performed
if [ -f "$FLAG_FILE" ]; then
    echo "Setup already completed. Skipping install."
    exit 0
fi

echo "Starting one-time setup..."

# 1. Update and install curl (if not present)
apt-get update && apt-get install -y curl binutils bsdmainutils bzip2 lib32gcc-s1 lib32stdc++6 netcat-openbsd pigz unzip

# Create ut2k4server user
USERNAME="ut2k4server"
if id "$USERNAME" &>/dev/null; then
    echo "User $USERNAME already exists."
else
    PASSWORD=$(tr -dc A-Za-z0-9 </dev/urandom | head -c 16)
    useradd -m -s /bin/bash "$USERNAME"
    echo "$USERNAME:$PASSWORD" | chpasswd
    echo "User '$USERNAME' created with password: $PASSWORD"
    echo $PASSWORD > "/tmp/${USERNAME}_password.txt"
fi

# Configure passwordless sudo access
SUDOERS_FILE="/etc/sudoers.d/$USERNAME"
echo "$USERNAME ALL=(ALL) NOPASSWD:ALL" > "$SUDOERS_FILE"
chmod 0440 "$SUDOERS_FILE"

# 2. Download and execute the UT2004 installer from LinuxGSM
su - "$USERNAME" -c "curl -Lo linuxgsm.sh https://linuxgsm.sh && chmod +x linuxgsm.sh && bash linuxgsm.sh ut2k4server && ./ut2k4server auto-install"
# Update the server's CD Key.
su - "$USERNAME" -c "curl -Lo cdkey.gnu https://github.com/siohaza/unreal-keygen/releases/download/v0.1.0/unreal-keygen-cli-0.1.0-x86_64-unknown-linux-gnu && chmod +x cdkey.gnu && ./cdkey.gnu ut2004 > /home/ut2k4server/serverfiles/System/cdkey && ./ut2k4server restart"

# 3. Add cronjobs to ut2k4server
cat << 'EOF' | crontab -u "$USERNAME" -
*/5 * * * * /home/ut2k4server/ut2k4server monitor > /dev/null 2>&1
0 0 * * 0 /home/ut2k4server/ut2k4server update-lgsm > /dev/null 2>&1
EOF

# 4. Create the flag file so this doesn't run again on next boot
if [ $? -eq 0 ]; then
    touch "$FLAG_FILE"
    echo "Setup successful. Flag file created."
else
    echo "Setup failed. Flag file not created; will retry on next boot."
    exit 1
fi