#!/bin/sh

destdir="/mnt/destination"
if [ -z "$(ls -1 "$destdir")" ]; then
	printf >&2 '%s\n' "${0##*/}: $destdir: directory is empty"
	exit 0
fi

WITHOUT_RC_COMPAT=1
. /etc/init.d/functions

unset \
	LANG \
	LANGUAGE \
	LC_CTYPE \
	LC_NUMERIC \
	LC_TIME \
	LC_COLLATE \
	LC_MONETARY \
	LC_MESSAGES \
	LC_PAPER \
	LC_NAME \
	LC_ADDRESS \
	LC_TELEPHONE \
	LC_MEASUREMENT \
	LC_IDENTIFICATION \
	LC_ALL \
	TEXTDOMAIN TEXTDOMAINDIR action \
	||:

# Taken action* and sendsigs from /etc/rc.d/init.d/halt (startup-0.9.8.11-alt1)

action_begin_msg()
{
	[ -z "$*" ] || printf '%s ' "$*"
}

action_end_msg()
{
	local rc=$1
	if [ "$BOOTUP" = color ]; then
		[ $rc = 0 ] && echo_success || echo_failure
	fi
	echo
}

action_passed_msg()
{
	[ "$BOOTUP" != color ] ||
		echo_passed
	echo
}

action()
{
	action_begin_msg "$1"
	shift
	$*
	local rc=$?
	action_end_msg "$rc"
	return $rc
}

sendsigs()
{
	action_begin_msg 'Asking all remaining processes to terminate'
	killall5 -15
	local rc=$?
	if [ "$rc" = 2 ]; then
		action_passed_msg
		return
	else
		action_end_msg "$rc"
	fi

	local seq=5
	if [ "$rc" = 0 ]; then
		for seq in 1 2 3 4 5; do
			killall5 -18 || break
			sleep 1
		done
	fi

	[ "$seq" = 5 ] || return 0
	action_begin_msg 'Killing all remaining processes'
	killall5 -9
	rc=$?
	if [ "$rc" = 2 ]; then
		action_passed_msg
	else
		action_end_msg "$rc"
	fi
}

exec_chroot()
{
	env -i PATH="$PATH" HOME=/root TMPDIR=/tmp chroot "$destdir" "$@"
}

# Remove installer specific packages from installed system
list="$(exec_chroot rpmquery -a alterator-autoinstall alterator-install* installer-group-*)"
action 'Removing installer specific packages from installed system' \
	exec_chroot rpmi -e -- $list

# Sync system buffers
sync

# Kill all processes
sendsigs

# Unmount new system
cut -d' ' -f2 /proc/mounts |
grep "^$destdir" |
sort -ur |
while read d; do
	umount -fl "$d"
done

# Remove cdrom
if [ "$METHOD" = 'cdrom' ]; then
	cddev="$(sed -n -e 's,^\(/dev/[^[:space:]]\+\) /image .*,\1,p' /proc/mounts)"
	if [ -b "$cddev" ]; then
		sed -i "/ $(printf %s "$destdir" |sed 's,/,\\/,g')/ d" /etc/mtab >/dev/null 2>&1
		umount -fl /image
		action 'Ejecting removable media' eject -p "$cddev"
	fi
fi

exit 0
