#! /bin/bash

# Usage: $0 file1.pdf file2.pdf
#   compares file1.pdf and file2.pdf by converting each page to bitmaps using
#   ghostscript and then using the 'compare' ImageMagick utility
#
# Copyright 2007 Sanjoy Mahajan.  Licensed under the GNU GPL version 2
# or (at your option) any later version.
#
# HISTORY
#   2007-01-15: First version
#

# configure these settings to your taste
# viewer=xloadimage
viewer=
dpi=100
imgformat=png256
ext=png
# mae is 'mean absolute error'.  rmse also seems to work
metric=mae
# If you have a custom paper size, define the papersize variable like
#   papersize="-dDEVICEWIDTHPOINTS=595.276 -dDEVICEHEIGHTPOINTS=841.89"
# A smarter script would figure out the papersize from the bounding box
papersize="-sPAPERSIZE=a4"

# FIXEDMEDIA and papersize setting are needed because otherwise image
# sizes could differ by O(1) pixel.
gs="gs -dFIXEDMEDIA ${papersize} -sDEVICE=${imgformat} -dNOPAUSE -dBATCH -dSAFER -q -r${dpi} -dTextAlphaBits=4"

# the rest of the script should be fine

if [ -z "$1" -o -z "$2" ]; then
  echo "Usage: $0 file1.pdf file2.pdf"
  exit 3
fi

if [ ! -r "$1" -o ! -r "$2" ]; then
  echo "$0: The files $1 and $2 must be readable"
  exit 4
fi

# generate the many page images in a temporary directory
d=`mktemp -d`
if ! [ -d "$d" -a -w "$d" ] ; then
  echo "$0: Cannot write in temporary directory $d.  Exiting..."
  exit 1
fi

# regexp to match the NNNN from %04d in the gs output filenames
numre='[0-9][0-9][0-9][0-9]'
# generate two sets of images, one image per page
$gs -sOutputFile=$d/one-%04d.$ext $1
$gs -sOutputFile=$d/two-%04d.$ext $2

# find the union of the page numbers (in case one pdf has more pages)
pages=`ls $d/{one,two}-$numre.$ext | sed "s/.*-\($numre\).$ext/\1/" | sort -un`

diffpages=
# compare each page
for p in $pages ; do
  if ! [ -e "$d/one-$p.$ext" ] ; then
    echo "$p: missing from $1"
    continue
  fi
  if ! [ -e "$d/two-$p.$ext" ] ; then
    echo "$p: missing from $2"
    continue
  fi
  db=`compare -metric ${metric} $d/{one,two}-$p.$ext $d/diff-$p.$ext | grep dB`
  if [ "$db" == "0 dB" ]; then
    rm -f $d/diff-$p.$ext
  else
    echo "[p.$p] $db diff [see $ext's in $d/]"
    diffpages="$diffpages $p"
  fi
done

if [ -n "$diffpages" ]; then
# To get a list of the page images with differences, uncomment next line:
# ls $d/diff-$numre.$ext
  if [ -n $viewer ]; then $viewer $d/diff-$numre.$ext >& /dev/null ; fi
fi
true
