#!/bin/sh -efu

# Remove all exists human users for oem install.

. install2-init-functions

failed=
kept_homes=

home_belongs_to_user() {
	# Neither a top-level directory nor a symlink is ever one user's own.
	case "$1" in
		/*/?*) ;;
		*) return 1 ;;
	esac

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

remove_user() {
	# The loop holds /etc/passwd on stdin, and $1 comes out of that file.
	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

	# userdel takes a -f as leave to remove a home that is not the user's,
	# and a copied system can name the root itself as somebody's home.
	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"

# The machine has to reach its buyer empty, so a directory that stays is a
# failure even once the account is gone. Only once every account has had its
# turn, though: two of them can name the same home, and the one that owns it
# takes it along whenever its line comes.
while IFS= read -r home; do
	[ -n "$home" ] && [ "$home" != / ] && [ -d "$destdir$home" ] || continue
	# One that belongs to root holds nothing of the user who named it.
	[ "$(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
