package=`basename $0 .postinst`
if [ -z "$base_package" ]; then
    base_package="$package"
fi
config="/etc/checkbox.d/$package.ini"

patch_configuration()
{
    version="$1"
    previous_version=""

    while [ -n "$version" ]; do
        patch_file=""
        patch_directory="/usr/share/$base_package/patches"
        [ ! -d "$patch_directory" ] && break

        # Sort patches using dpkg --compare-versions
        for temp_file in `find $patch_directory -type f`; do
            [ -n "$patch_file" ] \
                && patch_version=`basename $patch_file` \
                || patch_version=""
            temp_version=`basename $temp_file`
            if dpkg --compare-versions $temp_version lt-nl "$patch_version" && \
               dpkg --compare-versions $temp_version gt "$previous_version"; then
                patch_file=$temp_file
            fi
        done

        # If patch file is empty, all versions have been compared
        [ -z "$patch_file" ] && break

        # Apply the patch file if it is less than the given version
        patch_version=`basename $patch_file`
        if dpkg --compare-versions $version lt $patch_version; then
            $patch_file $package
        fi

        previous_version=`basename $patch_file`
    done
}

update_configuration()
{
    root_package=`echo $package | cut -d '-' -f '1'`

    # Create a temporary file to generate the suggested
    # configuration file.
    tempfile=`tempfile -m 0644 -p checkbox`

    # Update the temporary file with preseeded values.
    /usr/share/checkbox/install/config --output=$tempfile $package $base_package

    # Clobber the old config file.
    cp $tempfile $config

    # Now clear up the cruft.
    rm -f $tempfile
}

case "$1" in
    configure)
        # Patch and update configuration file
        patch_configuration "$2"
        update_configuration
        ;;
    abort-upgrade|abort-remove|abort-deconfigure)
        ;;
    *)
        echo "$0: didn't understand being called with \`$1'" 1>&2
        exit 0
        ;;
esac
