#! /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
}

modprobe_if_missing() {
    module=$1
    if ((cut -d" " -f1 /proc/modules | grep -q "^$module\$") ||
	(cut -d" " -f1 /proc/modules | sed -e 's/_/-/g' | grep -q "^$module\$")) ; then
	:
    else
	log-output -t autopartkit modprobe $module || true
    fi
}

# 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
modprobe_if_missing dm-mod
modprobe_if_missing lvm-mod
apt-install lvm2 || 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##
