#!/bin/bash

outputtype="ttf"

instanceparam="-i"

generateufo=true

xslfile="fix_wdth_axis.xsl"

for arg in $@
do
  if [ $arg == "otf" ]
  then
    outputtype=$arg
  elif [ $arg == "variable" ]
  then
    outputtype=$arg
    instanceparam=""
  elif [ $arg == "variable-cff2" ]
  then
    outputtype=$arg
    instanceparam=""
  elif [ $arg == "u" ]
  then
    generateufo=false
  elif [ $arg == "s"  ]
  then
    xslfile="fix_wdth_axis-shorter.xsl"
  fi

done

if [ "$generateufo" = true ]
then
  echo "Generating UFOs and designspace file from Glyphs source"
  glyphs2ufo --no-preserve-glyphsapp-metadata --propagate-anchors --generate-GDEF --write-public-skip-export-glyphs Junicode-width.glyphs
  if [ $? -ne 0 ]
  then
    echo "glyphs2ufo failed"
    exit 1
  fi
  echo "Cleaning up designspace file"
  xsltproc -o Junicode-width-fixed.designspace $xslfile Junicode-width.designspace
  if [ $? -ne 0 ]
  then
   echo "xsltproc failed"
   exit 1
  fi
fi

echo "building font(s)"
fontmake -o $outputtype $instanceparam -m "Junicode-width-fixed.designspace"
if [ $? -ne 0 ]
then
 echo "fontmake failed"
 exit 1
fi

if [ $outputtype == "variable" ]
then
  cp variable_ttf/Junicode-width-fixed-VF.ttf variable_ttf/JunicodeTwoBetaVF-Roman.ttf
  rm variable_ttf/Junicode-width-fixed-VF.ttf
fi
if [ $outputtype == "variable-cff2" ]
then
  cp variable_otf/Junicode-width-fixed-VF.otf variable_otf/JunicodeTwoBetaVF-Roman.otf
  rm -i variable_otf/Junicode-width-fixed-VF.otf
fi
exit 0
