#!/bin/sh

alterator_api_version=1
initinstall_dir="/usr/share/install2/initinstall.d"
livecd_initinstall_dir="/usr/lib/alterator/hooks/livecd-initinstall.d"
alteratord_socket_dir="/run/alteratord"

. alterator-sh-functions
a= . install2-sh-functions

PROG=initinstall
ALTERATOR_DESTDIR="${ALTERATOR_DESTDIR:-/mnt/destination}"

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

run_initinstall()
{
	# do nothing if scripts have already been executed
	if [ -s /tmp/initinstall.log ]; then
		# notify interface about finish
		notify "done #t"
		return 0
	fi

	# copy unique scripts from $destdir/$initinstall_dir to $initinstall_dir
	[ -d "$destdir/$initinstall_dir" ] &&
		find "$destdir/$initinstall_dir" -mindepth 1 -maxdepth 1 -type f -perm -u=x \
			-exec cp -n {} "$initinstall_dir" \;

	local f max counter=0
	max="$(find "$initinstall_dir" -mindepth 1 -maxdepth 1 -type f -perm -u=x |wc -l)"

	notify "init #t max $max"

	# run scripts
	for f in "$initinstall_dir"/* "$livecd_initinstall_dir"/*; do
		[ -f "$f" -a -x "$f" ] || continue

		echo "Running $f" >>/tmp/initinstall.log
		if "$f" >>/tmp/initinstall.log 2>&1; then
		    echo DONE >>/tmp/initinstall.log
		    notify "package \"${f##*/}\" step $counter"
		    counter=$(($counter + 1))
		    printf '%s %s - OK\n' "$(date +%T)" "$f" >&2
		else
		    echo FAILED >>/tmp/initinstall.log
		    notify "error \"${f##*/}\""
		    printf '%s %s - FAILED\n' "$(date +%T)" "$f" >&2
		    break
		fi
	done

	notify "package \" \" step $max"

	# notify interface about finish
	notify "done #t"
}

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

message_loop
