#!/usr/bin/env bash

user=$USER

if [ "$#" == 1 ]; then
	user=$1
fi

proc="0"

for pid in $(pidof hl2_linux)
do
	if sudo -H -u $user kill -0 $pid
	then
		proc=$pid
		break
	fi
done


if [ "$proc" == "0" ]
then
	echo "TF2 for $user is not running"
	continue
fi

echo Attaching to "$proc"

FILENAME=$(realpath "bin/libcathook.so")

echo loading "$FILENAME" to "$proc"

sudo killall -19 steam
sudo killall -19 steamwebhelper

sudo gdb -n -q -batch \
  -ex "attach $proc" \
  -ex "set \$dlopen = (void*(*)(char*, int)) dlopen" \
  -ex "call \$dlopen(\"$FILENAME\", 1)" \
  -ex "call dlerror()" \
  -ex 'print (char *) $2' \
  -ex "detach" \
  -ex "quit"

sudo killall -18 steamwebhelper
sudo killall -18 steam