detect_libnss_wrapper() {
  if $(which dpkg &>/dev/null); then
    libnss_wrapper_file=$(dpkg -S libnss_wrapper.so | awk -F' ' '{ print $2 }')
    return
  fi

  if [ -r /usr/lib/libnss_wrapper.so ]; then
      libnss_wrapper_file=/usr/lib/libnss_wrapper.so
  elif [ -r /usr/lib64/libnss_wrapper.so ]; then
      libnss_wrapper_file=/usr/lib64/libnss_wrapper.so
  else
      echo "no libnss_wrapper.so installed!"
      exit 1
  fi
}

# Set current user in nss_wrapper
USER_ID=$(id -u)
GROUP_ID=$(id -g)
echo "USER_ID: $USER_ID, GROUP_ID: $GROUP_ID"

# Attempt to set the username to the kasm username
USERNAME=${VNC_USER:-default}
# Make the username posix compliant
USERNAME=$(echo "$USERNAME" | sed -r 's#[^a-zA-Z0-9\._\-]#_#g')
if ! echo "$USERNAME" | grep -qP "^[a-zA-Z0-9_\.][a-zA-Z0-9_\-\.]*"; then
    USERNAME="default"
fi
export PS1="$USERNAME:\w\$ "

if [ x"$USER_ID" != x"0" ]; then

    NSS_WRAPPER_PASSWD=/tmp/passwd
    NSS_WRAPPER_GROUP=/etc/group

    cat /etc/passwd > $NSS_WRAPPER_PASSWD

    echo "${USERNAME}:x:${USER_ID}:${GROUP_ID}:Default Application User:${HOME}:/bin/bash" >> $NSS_WRAPPER_PASSWD

    export NSS_WRAPPER_PASSWD
    export NSS_WRAPPER_GROUP

    detect_libnss_wrapper
    echo "nss_wrapper location: $libnss_wrapper_file"
    export LD_PRELOAD="$libnss_wrapper_file"
fi
