#!/bin/bash

set -e

dir="$1"
shift

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

# XAUTHORITY, SSH_AUTH_SOCK and GPG_AGENT_INFO files can change after a re-login or a restart,
# so search for the passed one by podman/docker exec in the mount point of its parent directory
for env_var in XAUTHORITY SSH_AUTH_SOCK GPG_AGENT_INFO; do
  env_var_orig=${env_var}_ORIG
  var_val=${!env_var}
  var_val_orig=${!env_var_orig}
  if [ -n "$var_val" -a -n "$var_val_orig" ]; then
    if [ ! -r "$var_val" ]; then
      # the value should be in /run/user/<uid> or in /tmp, or else the parent directory is used
      run_dir="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
      if [[ "$var_val" == $run_dir/* ]]; then
        host_dir="$run_dir"
      elif [[ "$var_val" == /tmp/* ]]; then
        host_dir=/tmp
      else
        host_dir="$(dirname "$var_val")"
      fi
      new_val="${var_val/#$host_dir/${host_dir}-host}" # replace $host_dir by ${host_dir}-host
      if [ ! -r "$new_val" ]; then
        new_val="$var_val_orig"
      fi
      export $env_var="$new_val"
    fi
  else
    # remove unset variable in the container else apps can misbehave
    unset $env_var
  fi
done

# 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"
    break
  fi
fi

# reset to more conservative umask setting
umask 027

exec "$@"
