#!/usr/bin/env bash

line=$(pidof hl2_linux)
arr=($line)
inst=$1
if [ $# == 0 ]; then
  inst=0
fi

if [ ${#arr[@]} == 0 ]; then
  echo TF2 isn\'t running!
  exit
fi

if [ $inst -gt ${#arr[@]} ] || [ $inst == ${#arr[@]} ]; then
  echo wrong index!
  exit
fi

echo Running instances: "${arr[@]}"
echo Detaching from "${arr[$1]}"

if grep -q "$(realpath bin/libcathook.so)" /proc/"${arr[$1]}"/maps; then
  gdb -n -q -batch \
    -ex "attach  ${arr[$1]}" \
    -ex "set \$dlopen = (void*(*)(char*, int)) dlopen" \
    -ex "set \$dlclose = (int(*)(void*)) dlclose" \
    -ex "set \$library = \$dlopen(\"$(realpath bin/libcathook.so)\", 6)" \
    -ex "print \$library" \
    -ex "sharedlibrary ." \
    -ex "call \$dlclose(\$library)" \
    -ex "call \$dlclose(\$library)" \
    -ex "continue" \
	-ex "backtrace"
  echo "Detached"
else
  echo "not found!"
fi
