#!/bin/sh -e
# ***** BEGIN LICENSE BLOCK *****
# * Copyright (C) 2007  Alexey Gladkov <legion@altlinux.org>
# * Copyright (C) 2007  Dmitry V. Levin <ldv@altlinux.org>
# *
# * This program is free software; you can redistribute it and/or modify
# * it under the terms of the GNU General Public License as published by
# * the Free Software Foundation; either version 2 of the License, or
# * (at your option) any later version.
# *
# * This program is distributed in the hope that it will be useful,
# * but WITHOUT ANY WARRANTY; without even the implied warranty of
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# * GNU General Public License for more details.
# *
# * You should have received a copy of the GNU General Public License
# * along with this program; if not, write to the Free Software
# * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
# ***** END LICENSE BLOCK *****

WITH_ACTION=1
. install2-init-functions

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

# Taken sendsigs from /etc/rc.d/init.d/halt (startup-0.9.8.11-alt1)
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
}

# Run postinstall scripts
ls -1 "$postinstall_dir"/*|
    while read f ; do
	[ "$f" != "$postinstall_dir/*" ] || break
	[ -x "$f" ] || continue

	action "Running postinstall script [${f##*/}] " "$f"
    done

# Sync system buffers
sync

# Kill all processes
sendsigs

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

# Eject cdrom
if [ -b "$CDROMDEV" ]; then
    sed -i "/ $(printf %s "$destdir" |sed 's,/,\\/,g')/ d" /etc/mtab >/dev/null 2>&1
    umount -fl "$image_dir" ||:
    action 'Ejecting removable media' eject -p "$CDROMDEV"
fi
