#!/usr/bin/env bash

if [ $EUID == 0 ]; then
    echo "This script must not be run as root"
    exit
fi
[[ ! -z "$SUDO_USER" ]] && RUNUSER=$SUDO_USER || RUNUSER=$LOGNAME
line=$(pgrep -u $RUNUSER hl2_linux)
arr=($line)

if [ ${#arr[@]} != 0 ]; then
    echo TF2 Already Running!
    exit
fi

line=$(pgrep -u $RUNUSER steam)
arr=($line)

if [ ${#arr[@]} == 0 ]; then
    echo Steam not running! Starting it.
    steam > /dev/null 2>&1 &
    sleep 30
    echo Done starting Steam
fi

FILENAME="/tmp/.gl$(head /dev/urandom | tr -dc 'a-zA-Z0-9' | head -c 6)"

cp "bin/libcathook.so" "$FILENAME"

echo "Preloading cathook as $FILENAME!"
TF2_PATH=$(realpath ~/.steam/steam/steamapps/common/Team\ Fortress\ 2/)
pushd "$TF2_PATH"
LD_PRELOAD="$FILENAME" LD_LIBRARY_PATH="$TF2_PATH/bin" "$TF2_PATH/hl2_linux" -game tf > /dev/null 2>&1 &
echo "Game preloading!"
popd;
sleep 10;
rm "$FILENAME"
