package=`basename $0 .postinst`
config="/etc/checkbox.d/$package.ini"

patch_configuration()
{
    version="$1"
    previous_version=""
    base_package=`echo $package | sed -e 's/hwtest/checkbox/' -e 's/\(-cli\|-gtk\)//'`

    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
            # Package was renamed from hwtest to checkbox
            dpkg --compare-versions $patch_version lt "0.1-ubuntu13" \
                && patch_package=`echo $package | sed 's/checkbox/hwtest/'` \
                || patch_package=`echo $package | sed 's/hwtest/checkbox/'`
            $patch_file $patch_package
        fi

        previous_version=`basename $patch_file`
    done
}

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

    if [ "$base_package" != "hwtest" ]; then
        # 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

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

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

case "$1" in
    configure)
        # Workaround python-support which doesn't remove packages
        # under /usr/lib/python*
        for support_dir in python2.4 python2.5; do
            package_dir="/usr/lib/$support_dir/site-packages/$package"
            [ -e "$package_dir" ] && rm -fr $package_dir
        done

        # 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
