#!/bin/sh

rmlist="bottompaste.ps bottommask.ps bottomsilk.ps toppaste.ps topmask.ps topsilk.ps plated-drill.ps"
mlist="top.ps bottom.ps"
alist="topassembly.ps bottomassembly.ps"
clist="outline.ps"
#Rlist="bottomassembly.ps cu.top.ps"
fab="fab.ps"

for file in "$@"
do
  if [ ! -e $file ]; then continue; fi
  stem=`echo $file | sed -e 's/\.pcb$//'`
  #out="$file".ps

  pcb -x ps --drill-helper --media A4 --drill-copper --show-legend --multi-file             "$file" > /dev/null
  mv $stem.topassembly.ps $file.assembly_top_a.ps
  mv $stem.bottomassembly.ps $file.assembly_bottom_a.ps
  mv $stem.bottom.ps $file.cu_bottom_a.ps
  mv $stem.top.ps $file.cu_top_a.ps

  pcb -x ps --drill-helper --media A4 --drill-copper --show-legend --multi-file --mirror    "$file" > /dev/null
  mv $stem.topassembly.ps $file.assembly_top_m.ps
  mv $stem.bottomassembly.ps $file.assembly_bottom_m.ps
  for i in $mlist
  do
      mv $stem.$i $file.cu_$i
  done
  for i in $fab
  do
      mv $stem.$i $file.fab.mirror.ps
  done
  for i in $rmlist $alist $clist
  do
      rm -f $stem.$i
  done

  pcb -x ps --drill-helper --media A4 --drill-copper --show-legend --multi-file --fill-page "$file" > /dev/null
  for i in $rmlist $mlist
  do
      rm -f $stem.$i
  done
  for i in $clist $fab
  do
      if [ -f $stem.$i ]
      then
	  mv $stem.$i $file.$i
      fi
  done
  mv $stem.topassembly.ps $file.assembly_top.ps
  mv $stem.bottomassembly.ps $file.assembly_bottom.ps

  showdate=`stat -c "%y %n" $file`
  if git rev-parse --show-cdup > /dev/null 2>/dev/null $file
  then
      showdate=`git_show $file`;
  fi

  for i in $file.*.ps
  do
      mv $i tt
      sed -e 's/^%%DocumentMedia:.*/%%DocumentMedia: A4 595.27559 841.88976 0 "" ""/' < tt |
      sed -e "s/($file)/($showdate)/" > $i
      if ! grep -q ^showpage $i
      then
          echo showpage >> $i
      fi
  done
  rm -f tt

#  for i in $Rlist
#  do
#      a=$file.$i
#      mv $a tt
#      pstops -pa4 '1:0U@1(210mm,297mm)' $tt > $a 2>/dev/null
#  done
#  rm -f tt

  #echo $file $stem
  #echo $file.*.ps
  #cat $file.*.ps > t1.ps
  #ps2ps t1.ps $file.ps
  #rm t1.ps
  psjoin $file.*.ps > $file.ps
  ps2pdf $file.ps

#  pstops '0U(210mm,297mm)' $file.bottomassembly.ps $file.tt.ps
#  for i in cu.bottom.ps topassembly.ps tt.ps fab.ps; do cat $file.$i; done > t1.ps
#  #rm $file.tt.ps
#  ps2ps t1.ps t2.ps
#  ps2folded t2.ps
#  mv t2.2.ps $file.ps
#  rm t1.ps t2.*ps $file.tt.ps
done
