#!/bin/sh
# ***** BEGIN LICENSE BLOCK *****
# * Copyright (C) 2007  Alexey Gladkov <legion@altlinux.org>
# * Copyright (C) 2007  Dmitry V. Levin <ldv@altlinux.org>
# * Copyright (C) 2007  Anton V. Boyarshinov <boyarsh@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 *****

. /usr/share/alterator/build/backend3.sh
. install2-sh-functions

PROG="preinstall"

notify() {
	[ -z "$AUTOINSTALL" ] || return 0
	alterator-mailbox-send "$1" ||:
}

run_preinstall() {
	local f max counter=0
	max="$(find "$preinstall_dir" "$destdir/$preinstall_dir" -mindepth 1 -maxdepth 1 -type f -perm -u=x |wc -l)"

	notify "init #t max $max"

	# first run scripts from packages, because basic installer scripts can umount /image
	(ls "$destdir/$preinstall_dir"/*; ls "$preinstall_dir"/*) |
	    while  read f ; do
		[ -x "$f" ] || continue

		if "$f" >&2; then
		    notify "package \"${f##*/}\" step $counter"
		    counter=$(($counter + 1))
		    printf '%s - OK\n' "$PROG: $f" >&2
		else
		    notify "error \"${f##*/}\""
		    printf '%s - FAILED\n' "$PROG: $f" >&2
		    break
		fi
	    done

	notify "package \" \" step $max"
	notify "done #t"
	sync
}

on_message() {
        case "$in_action" in
        	write)
			echo "$PROG: write init" >&2
			if [ -z "$AUTOINSTALL" ]; then
				run_preinstall &
			else
				run_preinstall
			fi
			echo '()'
                        ;;
		*)
			echo '#f'
			;;
	esac
}

message_loop
