#!/bin/sh -e

WITH_ACTION=1
. install2-init-functions
. install2-remount-functions

md_not_synced() {
	local state=

	for md in /sys/block/md*/md/sync_action; do
		[ "$md" != '/sys/block/md*/md/sync_action' ] ||
			return 1
		read state < "$md"
		[ "$state" = "idle" ] ||
			return 0
	done

	return 1
}


if [ -z "$(ls "$destdir")" ]; then
	msg "$destdir: directory is empty"
	exit 0
fi

# Stop alteratord for correct unmount $destdir
	stop_alteratord

if [ -f "$destdir/_NEW_SYSTEM_" ];then
# Turn off splash screen
	[ ! -f /proc/splash ] || echo "0" >/proc/splash

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

# Run postinstall scripts
	for f in  "$postinstall_dir"/*; do
		[ -f "$f" -a -x "$f" ] || continue
		action "Running postinstall script [${f##*/}]" "$f" ||:
	done

# Speed-up and wait MD resync
	if grep -qws mdsync_nowait /proc/cmdline || [ -n "$DISPLAY" ] || [ -n "$WAYLAND_DISPLAY" ]; then
		: # Nothing to do
	elif md_not_synced; then
		echo 100000 >/proc/sys/dev/raid/speed_limit_min 2>/dev/null
		echo 500000 >/proc/sys/dev/raid/speed_limit_max 2>/dev/null
		tmpstat="$(mktemp -q "${TMPDIR-/tmp}/mdstat-XXXXXXXX.tmp")"
		msg1="Syncing MDRAID(s)"
		msg2="press ENTER to skip..."
		echo "$msg1, $msg2"
		tput cud1			# Move cursor down
		skip=
		while md_not_synced; do
			cols=$(tput cols)
			lines=$(tput lines)
			cat /proc/mdstat > "$tmpstat"
			rows=$(cat -- "$tmpstat" |wc -l |awk '{print $1;}')
			[ "$lines" -gt 0 -a "$rows" -gt 0 -a "$cols" -gt 0 ] \
				2>/dev/null || break
			if [ "$(($rows + 3))" -ge "$lines" ] 2>/dev/null; then
				tput cup 0 0	# Move to the up left corner
				tput ed		# Clear all terminal
				echo "$msg1, $msg2"
				tput cud1	# Move cursor down
				head -n $(($lines - 3)) -- "$tmpstat" |cut -c1-$cols
				tput cup 2 0	# Move cursor to begin of the row 3
			else
				tput ed		# Clear to the end of terminal
				head -n $rows -- "$tmpstat" |cut -c1-$cols
				for f in $(seq 1 $rows); do
					tput cuu1 # Move cursor up
				done
			fi
			unset cols rows lines

			# 5 sec timeout for press ENTER and continue
			if read -s -t 5 f; then
				skip=1
				break
			fi
		done

		# Move cursor up twice and clear to the end of terminal
		(echo cuu1; echo cuu1; echo ed) |tput -S

		if [ -z "$skip" ]; then
			action "$msg1" /bin/true
		else
			action_begin_msg "$msg1"
			action_passed_msg ||:
		fi
		rm -f -- "$tmpstat"
		unset tmpstat skip msg1 msg2
	fi

	rm -f -- "$destdir/_NEW_SYSTEM_"
fi

# Sync system buffers
sync

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

