#!/bin/sh -efu

. install2-init-functions

failed=
kept_homes=

home_belongs_to_user() {
	case "$1" in
		/*/?*) ;;
		*) return 1 ;;
	esac

	[ ! -L "$destdir$1" ] && [ -d "$destdir$1" ] &&
		[ "$(stat -c %u "$destdir$1")" = "$2" ]
}

remove_user() {
	if [ "$2" = with-home ]; then
		exec_chroot userdel -rf -- "$1" < /dev/null
	else
		exec_chroot userdel -f -- "$1" < /dev/null
	fi
}

while IFS=: read -r username _ uid _ _ home _; do
	[ "$username" != nobody ] || continue
	[ "$uid" -ge 1000 ] 2>/dev/null || continue

	if home_belongs_to_user "$home" "$uid"; then
		home_mode=with-home
		echo "92-oem-remove-human-users: removing $username of uid $uid with its home $home"
	else
		home_mode=without-home
		echo "92-oem-remove-human-users: removing $username of uid $uid, leaving $home alone"
		kept_homes="$kept_homes$home
"
	fi

	if ! remove_user "$username" "$home_mode"; then
		echo "92-oem-remove-human-users: userdel failed for $username" >&2
		failed=1
	fi
done < "$destdir/etc/passwd"

while IFS= read -r home; do
	[ -n "$home" ] && [ "$home" != / ] && [ -d "$destdir$home" ] || continue
	[ "$(stat -c %u "$destdir$home")" != 0 ] || continue

	echo "92-oem-remove-human-users: $home stays on the machine" >&2
	failed=1
done <<EOF
$(printf '%s' "$kept_homes" | sort -u)
EOF

ldm_state="$destdir/var/lib/ldm/.config/state-kde"
[ ! -f "$ldm_state" ] || sed -i '/lastUser=.*/d' "$ldm_state"

if [ -n "$failed" ]; then
	echo "92-oem-remove-human-users: the machine still carries a human user" >&2
	exit 1
fi
