#!/bin/bash

#
# Make errors visible upon `docker logs -f steam` command
#
exec 2>&1

#
# Befriend with grsecurity patched Linux kernel
#
# TODO: find a way how to set these attributes dynamically,
#       since this currently requires a Steam restart
#       when new content is obtained.
if [ -f /proc/sys/kernel/grsecurity/tpe_gid ]; then
  groupadd -r -g $(cat /proc/sys/kernel/grsecurity/tpe_gid) grsec-tpe
  usermod -aG grsec-tpe $USER
  setfattr -n user.pax.flags -v "m" \
            /lib/i386-linux-gnu/ld-2.19.so \
            $HOME/.local/share/Steam/ubuntu12_32/steam \
            $HOME/.local/share/Steam/ubuntu12_32/steamwebhelper \
            $HOME/.local/share/Steam/ubuntu12_32/gameoverlayui \
            $HOME/.local/share/Steam/steamapps/common/Half-Life/hl_linux
  # paxctl -c -v -m /lib/i386-linux-gnu/ld-2.19.so
fi

#
# Add a user to a detected "video" group
# so that it can access the nvidia devices
#
if [ -e /dev/nvidiactl ]; then
  GID=$(stat -c '%g' /dev/nvidiactl)
  groupadd -r -g $GID nvidia1
  if [ $? -eq 0 ]; then
    usermod -aG nvidia1 $USER
  else
    GROUP=$(stat -c '%G' /dev/nvidiactl)
    usermod -aG $GROUP $USER
  fi
fi

#
# This part is very important,
# since this lets Steam choose proper nvidia drivers (32 or 64 bit)
#
# Make sure the Steam docker image's paths are coming first
# and then the hosts's (/h1..20) mounted ones
export LD_LIBRARY_PATH="/lib:/lib64:/lib/i386-linux-gnu:/lib/x86_64-linux-gnu:$(echo /h{1..20}_{32,64} | tr ' ' ':')"
# GOOD export LD_LIBRARY_PATH="/lib/i386-linux-gnu:/lib/x86_64-linux-gnu:$(echo /h{1..20}_{32,64} | tr ' ' ':')"

#
# In order to avoid the inconsistency error, when launching `csgo_linux64`
# Inconsistency detected by ld.so: dl-open.c: 689: _dl_open: Assertion `_dl_debug_initialize (0, args.nsid)->r_state == RT_CONSISTENT' failed!
# Hint: to find out what's wrong, use `strace`
#
# 1) openSUSE's libpulsecommon-7.0.so vs Ubuntu's libpulsecommon-5.0.so
export LD_PRELOAD=$(find /h{1..20}_{32,64} -name "*libpulsecommon*" 2>/dev/null)

su -p user -c "steam $@"