#!/bin/sh

po_domain="alterator-livecd"
alterator_api_version=1

image_dir="${image_dir:-/image}"
target_dir="${target_dir:-/mnt/destination}"
initinstall_hooks_dir=/usr/lib/alterator/hooks/livecd-initinstall.d

. alterator-sh-functions
. alterator-livecd-functions

on_message() {
  case "$in_action" in
    write)
	local dev mpoint rest
	sort -r -k2,2 /proc/mounts|
	    while read dev mpoint rest; do
		[ "$mpoint" != "/" -a "$mpoint" != "$image_dir" ] || continue
		[ -n "${mpoint%%/.*}" ] || continue
		[ -b "$dev" ] || [ "${mpoint##$target_dir}" != "$mpoint" ] || continue
		if ! umount "$mpoint";then
		    local msg="$(printf "`_ "Unable to unmount %s\n"`" "$mpoint")"
		    write_error "$msg"
		    return
		fi
	    done

	if ! swapoff -a; then
	    write_error "`_ "Unable to turn off swap partitions"`"
	    return
	fi

	if ! mkdir -p -- "$target_dir"; then
	    write_error "`_ "Unable to create directory for new system"`"
	    return
	fi

	# Run initinstall scripts
	run-parts "$initinstall_hooks_dir"
	;;
	read)
	local languages= html_file=

	languages="$(printf '%s' "$in_language" |tr ';' ' ') all"
	html_file="$(find_htmlfile "livecd-start" "$languages")"
	if [ -s "$html_file" ]; then
		write_string_param "url" "$html_file"
	else
		write_error "`_ "File not found"`"
	fi
	;;
  esac
}

message_loop
