#!/bin/bash -e
# Copyright (c) 2009 Alon Swartz <alon@turnkeylinux.org> - all rights reserved

fatal() {
    echo "fatal: $@" 1>&2
    exit 1
}

usage() {
cat<<EOF
Syntax: $(basename $0) rootfs-dir conf
Executes the configuration script chrooted inside the root filesystem.

This uses the tklpatch-chroot sub-script.

Environment variables:

    TKLPATCH_DEBUG       Turn on debugging. Increases verbosity.
EOF
    exit 1
}
if [[ "$#" != "2" ]]; then
    usage
fi

[ -n "$TKLPATCH_DEBUG" ] && set -x

rootfs=$1
chroot_conf=$2

[ -d $rootfs ] || fatal "no such directory: $rootfs"
[ -x $chroot_conf ] || fatal "no such file / not executable: $chroot_conf"

echo "# executing config script $chroot_conf"
script_path=/tmp/tklpatch/$(basename $chroot_conf)
mkdir -p $rootfs/$(dirname $script_path)

# copy conf directory if script is not named 'conf' (advanced hooks)
if [ $(basename $script_path) == "conf" ]; then
    cp $chroot_conf $rootfs/$script_path
else
    cp -a $(dirname $chroot_conf)/* $rootfs/$(dirname $script_path)
fi

chmod +x $rootfs/$script_path

tklpatch-chroot $rootfs $script_path

rm -rf $rootfs/tmp/tklpatch
