#!/bin/bash

VERSION=0.1.4

function ngc_position {
  ifn="$1"

  offsetx=10
  offsety=10

  if [[ "$ifn" == "" ]] ; then
    echo "provide file"
    exit 1
  fi

  dos2unix $ifn
  sed -i 's/;.*//' $ifn

  mx=`ngc_bounds $ifn | grep min_x | cut -f2 -d' '`
  my=`ngc_bounds $ifn | grep min_y | cut -f2 -d' '`

  shiftx=` echo "-($mx) + $offsetx" | bc -l`
  shifty=` echo "-($my) + $offsety" | bc -l`

  tfn=`mktemp`

  #echo "G0 F5000" > $tfn
  grecode -shift "$shiftx" "$shifty" $ifn | \
    grep -v '^(' >> $tfn 2> /dev/null
  mv $tfn $ifn

  rm -f $tfn
}

tmpfn=`mktemp`

for fn in `ls ../Popufare*.scad  | grep -v PopufareHousingCommon.scad ` ; do
  bfn=`basename $fn .scad`
  svg="$bfn.$VERSION.svg"
  ngc="$bfn.$VERSION.ngc"

  echo "## $bfn"

  basedir=`dirname $( pwd ) `

  echo "include <$basedir/$bfn.scad>" > $tmpfn
  echo "${bfn}Plate();" >> $tmpfn

  openscad -o "$svg" "$tmpfn"
  svg2ngc "$svg" 2> /dev/null
  ngc_position "$ngc" 2> /dev/null

  sed -i 's/F800/F150/g' "$ngc"
  sed -i 's/G0\(.*\)S\(.*\)/G0\1 F5000 S\2/g' "$ngc"

done

rm $tmpfn
