#!/bin/bash

set -e

dir="$1"
shift

if [ -n "$dir" -a -d "$dir" ]; then
  cd "$dir"
fi

# In case NVIDIA driver has been updated, the updated libraries and other files may need to be
# linked again, so check for a missing library file and invoke the setup script if present
nvidia_setup="$YBOX_TARGET_SCRIPTS_DIR/nvidia-setup.sh"
if [ -e "$nvidia_setup" ]; then
  function is_nvidia_valid() {
    nvidia_glx_libs="$(echo /usr/local/nvidia/lib*/libGLX_nvidia.so.*)"
    for lib in $nvidia_glx_libs; do
      if [ ! -r "$lib" ]; then
        return 1
      fi
    done
    return 0
  }
  if ! is_nvidia_valid; then
    lock_file="/tmp/nvidia-setup.lock"
    (
      # ensure no other instance is trying the same (wait for reasonable time before continuing)
      lock_fd=100
      flock -x -w 60 $lock_fd || /bin/true
      trap "flock -u $lock_fd || /bin/true" 0 1 2 3 4 5 6 7 8 10 11 12 13 14 15
      if ! is_nvidia_valid; then
        # set umask for root execution to ensure that other users have read/execute permissions
        umask 022
        sudo /bin/bash "$nvidia_setup" || /bin/true
      fi
    ) 100>"$lock_file"
  fi
fi

# reset to more conservative umask setting
umask 027

exec "$@"
