#!/usr/bin/env bash

if [ $UID == "0" ]; then
	echo "Don't run as root!"
	exit
fi

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

echo Attaching to "$proc"

if sudo grep -q "libcathook.so" /proc/"$proc"/maps; then
	echo already loaded
	exit
fi

# pBypass for crash dumps being sent
# You may also want to consider using -nobreakpad in your launch options.
sudo rm -rf /tmp/dumps # Remove if it exists
sudo mkdir /tmp/dumps # Make it as root
sudo chmod 000 /tmp/dumps # No permissions

cp "bin/libcathook.so" /tmp

FILENAME=/tmp/libcathook.so

echo loading "$FILENAME" to "$proc"

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"
  
rm /tmp/libcathook.so