#!/bin/bash
set -e

###############################
# Unturned Dedicated Server Installer
# Works on Ubuntu/Debian systems
###############################

echo "=== Updating system ==="
sudo apt update -y
sudo apt install -y lib32gcc-s1 curl wget tar

echo "=== Creating steam user ==="
if ! id "steam" &>/dev/null; then
    sudo useradd -m steam
fi

echo "=== Making directories ==="
sudo -u steam mkdir -p /home/steam/steamcmd
sudo -u steam mkdir -p /home/steam/unturned

echo "=== Downloading SteamCMD ==="
cd /home/steam/steamcmd
sudo -u steam wget https://steamcdn-a.akamaihd.net/client/installer/steamcmd_linux.tar.gz
sudo -u steam tar -xvzf steamcmd_linux.tar.gz

echo "=== Installing Unturned Server ==="
sudo -u steam ./steamcmd.sh +login anonymous \
    +force_install_dir /home/steam/unturned \
    +app_update 304930 validate \
    +quit

echo "=== Creating start script ==="
cat << 'EOF' | sudo tee /home/steam/unturned/start_server.sh > /dev/null
#!/bin/bash

# Change ServerName to whatever you want
SERVER_NAME="MyServer"

# Start Unturned server
./ServerHelper.sh +LanServer/$SERVER_NAME
EOF

sudo chmod +x /home/steam/unturned/start_server.sh
sudo chown steam:steam /home/steam/unturned/start_server.sh

echo "=== Installation complete! ==="
echo "Run server with:"
echo "sudo -u steam /home/steam/unturned/start_server.sh"
