#!/usr/bin/env bash
set -Eeuo pipefail

possibles=( nobody daemon irc www-data )
if [ -n "${AUTOPKGTEST_NORMAL_USER:-}" ]; then
	possibles=( "$AUTOPKGTEST_NORMAL_USER" "${possibles[@]}" )
fi
if self="$(id -un 2>/dev/null)"; then
	# try "self" last because that's the least interesting test (root becoming root)
	possibles+=( "$self" )
fi

gosuAs=
expect=
for user in "${possibles[@]}"; do
	if grep -qP "^\Q${user}\E:" /etc/passwd && expect="$(id "$user" 2> /dev/null)"; then
		gosuAs="$user"
		break
	fi
done

if [ -z "$gosuAs" ]; then
	cat >&2 <<-EOF

		error: AUTOPKGTEST_NORMAL_USER not set (or not usable) and could not find a suitable alternative user
		tried: ${possibles[*]}

	EOF
	id "${possibles[@]}" >&2 || :
	exit 1
fi

actual="$(gosu "$gosuAs" id)"

if [ "$actual" != "$expect" ]; then
	cat >&2 <<-EOF

		error: unexpected output ("gosu $gosuAs id"):
		actual: $actual
		expect: $expect

	EOF
	exit 1
fi
