#!/bin/bash
#
# First argument: name of board or schematic file
#   ie "freeduino-116.brd"
# Addition arguments: layers to visualize
#   ie "top pads vias"  or "tplace tdocu"
#
# Creates gerbers of the given layers for the file and any backups of
# that file that exist, and loads them up into gerbv in a way designed
# to highlight minor changes.
#
#
EAGLE=/Applications/EAGLE5.10/EAGLE.app/Contents/MacOS/EAGLE
#
DIR=`dirname $1`
echo DIR=$DIR
BASE=`basename $1`
echo BASE=$BASE
BRD=`basename $1 .brd`
echo BRD=$BRD
SCH=`basename $1 .sch`
echo SCH=$SCH
TMP=/tmp/eagleback.$$
echo TMP=$TMP  proc = $$
PRJ=$TMP/gerv.prj
#
# Create a temporary directory for our files
mkdir $TMP
# Initialize a gerbv "project" file.
#
#
if [ $BASE != $BRD ] ; then
  echo We have a BOARD: $BRD in directory $DIR
  EXT=brd
  function mkfilename {
      echo $1$BRD.b#$2
  }
elif [ $BASE != $SCH ] ; then
  echo We have a SCHEMATIC: $SCH in directory $DIR
  EXT=sch
  function mkfilename {
      echo $1$SCH.s#$2
  }
fi

#
# Create a gerber of the (most recent) .BRD file.
  $EAGLE -X -dGERBER_RS274X -o$TMP/Current $1 $2 $3 $4 $5 $6 $7
#
#
# now, for any backup files that exist, copy them into the tmp
# directory (with a .brd filetype so that EAGLE will recognize it)
# and make a gerber of them as well.
# Also build a list of the found files in $BACKUPS
BACKUPS=
  for f in 1 2 3 4 5 6 7 8 9 ; do
    THISFILE=`mkfilename $DIR/ $f`
    if [ -e $THISFILE ] ; then
      echo processing `mkfilename "" $f`
      OLDEST=$f
      BACKUPS="$f $BACKUPS"
      cp $THISFILE $TMP/tmp.$EXT
      $EAGLE -X -dGERBER_RS274X -o`mkfilename $TMP/ $f` $TMP/tmp.$EXT $2 $3 $4 $5 $6 $7
    fi
  done

# Next, create the gerbv "project" file containing color assignments
#  This is done separately because we want to know which backup is last,
#  so that initially "make visible" the oldest backup and current file.
# I haven't seen documentation for the gerbv project file format; the values
#  and structure used here are derived by manually editing a project and
#  looking at the saved file.
  echo \(gerbv-file-version! \"2.0A\"\) >$PRJ
  echo \(define-layer\! -1 \(cons \'filename \"$TMP\"\)\(cons \'visible \#f\)\(cons \'color \#\(0 0 0\)\)\) >>$PRJ
echo Backups = $BACKUPS  OLDEST = $OLDEST
  for f in $BACKUPS ; do
    if [ x$f = x$OLDEST ] ; then
      echo \(define-layer\! $f \(cons \'filename \"`mkfilename "" $f`\"\)\(cons \'color \#\(49344 8224 0\)\)\) >>$PRJ
    else
      echo \(define-layer\! $f \(cons \'filename \"`mkfilename "" $f`\"\)\(cons \'visible \#f\)\(cons \'color \#\(49344 4112 0\)\)\) >>$PRJ
    fi
  done
  echo \(define-layer\! 0 \(cons \'filename \"Current\"\)\(cons \'visible \#t\)\(cons \'color \#\(49344 3855 0\)\)\) >>$PRJ
  echo \(set-render-type\! 1\) >>$PRJ


gerbv -p $PRJ
