#! /bin/sh -e

. /usr/share/debconf/confmodule

template=autopartkit/partition_table

log() {
    logger -t autopartkit "$@"
}

run_parts() {
    partsdir="$1"

    for script in "$partsdir"/*; do
	if [ -x "$script" ] ; then
	    if "$script" "$template" ; then
		:
	    else
		log "error: Fragment '$script' returned an error: $?."
	    fi
	else
	    log "error: Fragment '$script' is not executable."
	fi
    done
}

# Try to load LVM support, and make sure the user tools are installed into
# /target/.  It should be safe to try both alternatives, as only the working
# one will be activated at boot.
log-output -t autopartkit depmod -a || true
log-output -t autopartkit dm-mod || true
log-output -t autopartkit lvm-mod || true
apt-install lvm2 || true
apt-install lvm10 || true

# Run all scripts to choose table file
run_parts /usr/lib/autopartkit.d

tablefile=`debconf-get $template 2>&1`

if [ -z "$tablefile" -o ! -f "$tablefile" ] ; then
    log "Unable to find table file '$tablefile'"
    exit 1
fi

if autopartkit "$tablefile" ; then
    log "info: autoparkit ran successfully using table file '$tablefile'."
else
    # This should use debconf to report the error.
    log "error: autopartkit failed."
    exit 1
fi

log "info: creating /target/etc/fstab."
/usr/lib/partconf/mkfstab

##DEBHELPER##
