set -eu
USER_STORE=/var/lib/dh-sysuser/user

home=%HOME%
username=%USERNAME%
package=%PACKAGE%

# Since according to POSIX, * glob expands to itself,
# if it fails to match anything, this function does not
# work properly, if $1 is empty.
count_files_in () {
	dir=$1
	set --
	for file in "$dir"/* ; do
		set -- "$@" "$file"
	done
	unset dir
	printf "%d" "$#"
}

store="$USER_STORE/$username"
mkdir -p "$store/_meta"
# -*- sh -*-
# Count how many packages already requested presence of
# $username. _meta directory is just created and adds 1 to count
# and fulfills precondition of `count_files_in'.

if [ $(count_files_in "$store") = 1 ] ; then

	# So, there is only 1 entry in "$USER_STORE/$username". It
	# means that nobody yet requested presence of $username, and
	# we must create it our self.

	set -- --shell /usr/sbin/nologin "$username"

	# If $username was created in past, but after that was
	# removed, since all packages that needed it was purged,
	# preferred uid is left behind. If possible, we reuse it.

	if [ -f "$store/_meta/id" ] ; then
		uid=$(cat "$store/_meta/uid")
		set -- --uid "$uid" "$@"
	fi

	# Lintian complains, if it fails to find --home options.
	# And sure, it can't understand that it is hidden in $@.
	if ! adduser --home "${home}" --system "$@" ; then

		# XXX: man page is explicit, that adduser can fail for
		# tons of undocumented reasons, but here we believe,
		# the reason is that uid is already taken.

		# Then we have to give up explicit uid command options.
		shift 2
		adduser --home "${home}" --system "$@"
	fi
fi

# Here $username already exists.
getent passwd "$username" | cut -d: -f3 > "$store/_meta/uid"
touch "$store/$package"
