#!/bin/sh

. /usr/share/alterator/build/backend3.sh
PROG="basesystem"
destdir="/mnt/destination"
manifest="/tmp/metadata/basesystem.manifest"

use_swap() {
	[ -f "/tmp/fstab" ] &&
		[ ! -f "/etc/fstab.swap" ] &&
		touch "/etc/fstab.swap" &&
		grep '\<swap\>' /tmp/fstab >> /etc/fstab ||
		return 0
	swapon -a
}

on_message() {
        case "$in_action" in
		write)
			if [ ! -s "$manifest" ]; then
				printf '(error "Manifest for basesystem empty or not found")\n'
				return 0
			fi
			use_swap
			if [ -z "$AUTOINSTALL" ]; then
				/usr/sbin/install2-manifest "$manifest" &
			else
				/usr/sbin/install2-manifest "$manifest"
			fi
			echo '()'
			;;
		unmount)
			cut -d' ' -f2 /proc/mounts |
				fgrep "$destdir" |
				sort -ur |
			while read d; do
				umount -fl "$d"
				printf %s\\n "$PROG: umount $d" >&2
			done
			echo '()'
			;;
		*)
			echo '#f'
			;;
        esac
}

message_loop
