#!/bin/sh
# Copyright (C) 2012  SUSE / Cédric Bosdonnat <cbosdonnat@suse.com>
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

function print_help()
{
    cat << EOF
$0 --word|-mso path/to/mso.pdf --writer|-lo path/to/lo.pdf --page|p page_number

This script creates an XCF file containing the corresponding pages from
the two PDF files as layers. This eases the comparison of the two outputs in Gimp.
EOF
}

WORD_PDF=
WRITER_PDF=
PAGE=

while [ "$1" != "" ]; do
    case "$1" in
        "--word" | "-mso" )
            shift
            WORD_PDF=$1
            ;;
        "--writer" | "-lo" )
            shift
            WRITER_PDF=$1
            ;;
        "--page" | "-p" )
            shift
            PAGE=$1
            ;;
        *)
            print_help
            exit 1;;
    esac
    shift
done

if test "z$WORD_PDF" = "z"; then
    echo -e "Missing Word PDF file\n"
    print_help
    exit 1
fi

if test "z$WRITER_PDF" = "z"; then
    echo -e "Missing Writer PDF file\n"
    print_help
    exit 1
fi

if test "z$PAGE" = "z"; then
    echo -e "Missing Page number\n"
    print_help
    exit 1
fi

WORD_PAGE=word-$PAGE.tif
WRITER_PAGE=writer-$PAGE.tif
RESULT_PAGE=page-$PAGE.xcf

echo "Extracting page from Word PDF output..."
convert -density 288 $WORD_PDF[$PAGE] -channel a -evaluate set 100% $WORD_PAGE 2>/dev/null

echo "Extracting page from Writer PDF output..."
convert -density 288 $WRITER_PDF[$PAGE] -channel a -evaluate set 100% $WRITER_PAGE 2>/dev/null

echo "Creating XCF file..."
gimp -i -c -d -f -s -n -b \
		'(define 
            (create-image wordfilename writerfilename targetfilename)
		 (let*
            (
                (image (car (gimp-file-load RUN-NONINTERACTIVE wordfilename wordfilename)))
                (wordlayer (car (gimp-image-get-active-layer image)))
                (writerlayer (car (gimp-file-load-layer RUN-NONINTERACTIVE image writerfilename)))
            )
    		(gimp-image-add-layer image writerlayer -1)
	    	(gimp-layer-set-opacity writerlayer 50.0)
            (gimp-drawable-set-name writerlayer "Writer")
            (gimp-drawable-set-name wordlayer "Word")
		    (gimp-xcf-save RUN-NONINTERACTIVE image wordlayer targetfilename targetfilename)
    		(gimp-image-delete image)))

		(create-image "'$PWD/$WORD_PAGE'" "'$PWD/$WRITER_PAGE'" "'$PWD/$RESULT_PAGE'")
		(gimp-quit 0)' >/dev/null 2>&1

rm $WORD_PAGE $WRITER_PAGE
