#!/bin/sh

# SPDX-License-Identifier: LGPL-2.1+
#
# Copyright (C) 2018 Collabora ltd.
# @author Emanuele Aina <emanuele.aina@collabora.com>

test_description="Use nss_wrapper to pretend the current user is not in the db"

. /usr/share/sharness/sharness.sh

test_debug "export NSS_WRAPPER_DEBUGLEVEL=3"

get_passwd_entry () {
  USERID=$1

  env -i \
    ${HOME+HOME=$HOME} \
    ${NSS_WRAPPER_DEBUGLEVEL+NSS_WRAPPER_DEBUGLEVEL=$NSS_WRAPPER_DEBUGLEVEL} \
    ${NSS_UNKNOWN_HOME+NSS_UNKNOWN_HOME=$NSS_UNKNOWN_HOME} \
    LD_PRELOAD=libnss_wrapper.so \
    NSS_WRAPPER_PASSWD=/dev/null \
    NSS_WRAPPER_GROUP=/dev/null \
    NSS_WRAPPER_MODULE_SO_PATH="${MESON_BUILD_ROOT}/libnss_unknown.so" \
    NSS_WRAPPER_MODULE_FN_PREFIX=unknown \
    getent passwd "$USERID"
}

export HOME="/fakehome"

entry=$(get_passwd_entry $(id -u))
test_debug "echo entry = '$entry'"
test_expect_success 'A passwd entry is returned' \
  'test -n "$entry"'

username=$(echo "$entry" | cut -f 1 -d ":")
shell=$(echo "$entry" | cut -f 7 -d ":")
home=$(echo "$entry" | cut -f 6 -d ":")

test_debug "echo username = '$username'"
test_expect_success 'A made-up username is returned for the unknown user' \
  'test "$username" = uid-$(id -u)'

test_debug "echo shell = '$shell'"
test_expect_success 'The nologin command is returned as the user shell' \
  'test "$shell" = /sbin/nologin'

test_debug "echo home = '$home'"
test_expect_success 'The $HOME env var is returned as the user homedir' \
  'test "$home" = "$HOME"'

unset HOME
entry=$(get_passwd_entry $(id -u))
home=$(echo "$entry" | cut -f 6 -d ":")
test_debug "echo entry = '$entry'"
test_debug "echo home = '$home'"
test_expect_success 'Fallback to "/" if $HOME is not set' \
  'test "$home" = "/"'

export NSS_UNKNOWN_HOME="/unknownhome"
export HOME="/fakehome"
entry=$(get_passwd_entry $(id -u))
home=$(echo "$entry" | cut -f 6 -d ":")
test_debug "echo entry = '$entry'"
test_debug "echo home = '$home'"
test_expect_success 'Check that NSS_UNKNOWN_HOME overrides HOME' \
  'test "$home" = "$NSS_UNKNOWN_HOME"'

test_done
