#! /bin/sh

usage ()
{
  echo Usage: 
  echo \\tpcbdiff firstfile secondfile
  echo \\tView a graphical diff of PCB files
  echo
  echo \\tTo use with git, just place this script in your PATH and do
  echo \\tgit difftool -x pcbdiff ...
  echo
  echo \\tTo use with mercurial, add the following lines to your .hgrc:
  echo \\t\\t[extensions]
  echo \\t\\thgext.extdiff =
  echo \\t\\t[extdiff]
  echo \\t\\tcmd.pcbdiff = /PATH/TO/pcbdiff
  echo \\tthen to invoke it, do
  echo \\thg pcbdiff ...
  echo
  echo \\tTo use with subversion, place it in your PATH and do
  echo \\tsvn diff --diff-cmd pcbdiff ...

  echo \\tRequirements: Imagemagick and gschem be installed
}

PCB=`which pcb`
if test -z "${PCB}"; then
  MISSING=pcb
fi

CONVERT=`which convert`
if test -z "${CONVERT}"; then
  MISSING=convert
fi

COMPOSITE=`which composite`
if test -z "${COMPOSITE}"; then
  MISSING=composite
fi

VIEWER=`which display`
if test -z "${VIEWER}"; then
  MISSING=display
fi

if test -z "${MISSING}"; then
  true
else
  echo "Binary for \"${MISSING}\" not found." >&2
  echo "Either it is not installed, or not in your PATH" >&2
  exit 1
fi

#In case the script was invoked with extra option arguments, throw them away
shift `expr $# - 2`

LEFTFILE="${1}"
RIGHTFILE="${2}"
if test -d "${LEFTFILE}" -o -d "${RIGHTFILE}"
  then echo "ERROR: pcbdiff cannot diff entire directories"
  exit 1
fi

LEFTPNG=`mktemp --tmpdir pcbdiff.XXXXXXXXXX`
RIGHTPNG=`mktemp --tmpdir pcbdiff.XXXXXXXXXX`
LEFTBNW=`mktemp --tmpdir pcbdiff.XXXXXXXXXX`
RIGHTBNW=`mktemp --tmpdir pcbdiff.XXXXXXXXXX`
DIFFPNG=`mktemp --tmpdir pcbdiff.XXXXXXXXXX`

"${PCB}" -x png --dpi ${PCBDIFF_DPI:-200} --photo-mode --outfile ${LEFTPNG} "${LEFTFILE}"
"${PCB}" -x png --dpi ${PCBDIFF_DPI:-200} --photo-mode --outfile ${RIGHTPNG} "${RIGHTFILE}"
"${CONVERT}" -colorspace gray $LEFTPNG $LEFTBNW
"${CONVERT}" -colorspace gray $RIGHTPNG $RIGHTBNW
"${COMPOSITE}" -stereo 0 $LEFTBNW $RIGHTBNW $DIFFPNG
"${VIEWER}" $DIFFPNG
rm $LEFTPNG
rm $RIGHTPNG
rm $LEFTBNW
rm $RIGHTBNW
rm $DIFFPNG
