#!/bin/bash
# Bootstraps Steam on a headless server without requiring X11 interaction.
# Bypasses the zenity license dialog that normally hangs headless installations.

set -e

# Get the current version expected by the Debian package
if [ -f "/usr/games/steam" ]; then
    VERSION=$(grep -oP 'version="\K[^"]+' /usr/games/steam || echo "1.0.0.85")
else
    VERSION="1.0.0.85"
fi

echo "Bootstrapping Steam headless installation (Version $VERSION)..."

STEAMDIR="$HOME/.steam/debian-installation"
mkdir -p "$STEAMDIR"

echo "Downloading Steam bootstrap tarball..."
curl -fsSL "https://repo.steampowered.com/steam/archive/beta/steam_${VERSION}.tar.gz" | tar -xz -C "$STEAMDIR"

echo "Extracting embedded Steam runtime..."
tar -xJf "$STEAMDIR/steam-launcher/bootstraplinux_ubuntu12_32.tar.xz" -C "$STEAMDIR"

echo "Marking installation version..."
mkdir -p "$STEAMDIR/deb-installer"
echo "$VERSION" > "$STEAMDIR/deb-installer/version"

echo "Creating required API symlinks..."
ln -fns "$STEAMDIR" "$HOME/.steam/steam"
ln -fns "$STEAMDIR" "$HOME/.steam/root"

echo "Steam is now bootstrapped."
echo "Run 'DISPLAY=:0 steam' to trigger the background update (takes ~3 minutes)."
