#!/bin/bash

if [ $# -lt 1 ]
then
    echo "Usage: build_font [-t | -o] [-i] [-a] [-w] file.glyphs"
    echo " Type \"build_font -h\" for help."
    exit 1
fi

outputType="v"

glyphsfile="nofile"

fontname="nofont"

instanceScript="del_instances_vf.xsl"

autohint=0

createwoff=0

for arg in $@
do
    if [ $arg == "-h" ] || [ $arg == "--help" ]
    then
      echo "Usage: build_font [-t | -o] [-i] [-a] [-w] file.glyphs"
      echo ""
      echo "A script for building variable and static versions of the Elstob font."
      echo "It does several things that are specific to Elstob and probably unsuitable"
      echo "for other fonts. Either run this script in the sources directory or copy"
      echo "all files from the sources directory to a build directory and run it there."
      echo ""
      echo "  -t Builds static TrueType fonts instead of a variable font"
      echo "  -o Builds static CFF fonts instead of a variable font"
      echo "  -a Autohint the variable font with ttfautohint-vf"
      echo "  -i Generate a shorter collection of instances"
      echo "  -w Create a woff2 version of the variable font"
      echo ""
      echo "To create a font with a different family name (e.g. ElstobO), change the"
      echo "family name in Glyphs."
      exit 0
    fi
    if [ $arg == "-t" ]
    then
      outputType="s"
      instanceScript="del_instances.xsl"
    elif [ $arg == "-o" ]
    then
      outputType="o"
      instanceScript="del_instances.xsl"
    elif [ $arg == "-a" ]
    then
  	 autohint=1
    elif [ $arg == "-w" ]
    then
  	createwoff=1
    elif [ $arg == "-i" ]
    then
  	instanceScript="del_instances_shorter.xsl"
    elif [ -f $arg ]
    then
	     if [ ${arg##*.} == "glyphs" ]
	     then
	        glyphsfile=$arg
	        ff=$(basename -- $arg)
	        fontname=${ff%.*}
	     else
	        echo "${arg} appears not to be a Glyphs file"
	        exit 1
	     fi
    else
  	    echo "Unknown argument or non-existent file ${arg}"
        exit 1
    fi
  done

if [ $glyphsfile == "nofile" ] || [ $fontname == "nofont" ]
then
    echo "Could not derive the filename or fontname."
    exit 1
fi

if [[ $fontname == *"Italic"* ]]
then
    fonttype="italic"
else
    fonttype="roman"
fi

des="master_ufo/${fontname}.designspace"

echo "Generating master UFOs and designspace files"
glyphs2ufo --propagate-anchors --generate-GDEF --no-store-editor-state -m master_ufo -d $des $glyphsfile
if [ $? -ne 0 ]
then
    echo "Failed to generate UFO and designspace"
    exit 1
fi

familyname=`gsed -n '1,/<source.*familyname/s/.*familyname="\([^"]*\)"[^\n]*/\1/p' $des`
echo "Building font(s) with family name \"${familyname}\""

# Every glyph with a "us" anchor also needs a "_us" anchor or fontmake (glyphsLib,
# I think) will mess up the anchors for that glyph. But there is no requirement
# that anchors must be paired this way, and it's easy to imagine the extraneous
# anchors causing problems (though I don't know that it has). As it is easy to
# strip the extraneous anchors out of the UFO, it's best that we do so.

Echo "Removing extraneous anchors"

for u in `gsed -n '/<source.*filename/s/.*filename="\([^"]*\)"[^\n]*/\1/p' $des`
do
    for fff in `grep -l "anchor.*\"_us\"" master_ufo/$u/glyphs/*.glif`
    do
	if [[ ! $fff == *"usabovecomb.glif"* ]]
	then
	    xsltproc -o $fff del_usanchor.xsl $fff
	    if [ $? -ne 0 ]
	    then
		exit 1
	    fi
	fi
    done
done

# The Glyphs file has more instances than needed--some only there to hold down
# the corners of the design space. There are standard collections of instances
# for the variable font, the desktop set (ElstobD), and the web static set.

if [ $fonttype == "italic" ]
then
    sn="Grade Italic"
else
    sn="Grade"
fi
grep -q "stylename=\"${sn}\"" $des
if [ $? -eq 0 ]
then
    echo "Removing unnneeded instances"
    xsltproc -o $des $instanceScript $des
fi

# build the fonts.
if [ $outputType = "s" ];
then
  echo "Running fontmake to build static TrueType instances"
  fontmake -o ttf -a -i -m $des
  if [ $? -ne 0 ]
  then
    echo "fontmake failed"
    exit 1
  fi
  cd autohinted/instance_ttf
  if [ $fonttype == "italic" ]
  then
    for ff in "${familyname}*Italic.ttf"
    do
      gftools fix-dsig --autofix $ff
    done
  else
    for ff in `find . -maxdepth 1 -name "${familyname}*.ttf" -not -name "*Italic.ttf"`
    do
      gftools fix-dsig --autofix $ff
      gftools-fix-hinting.py $ff
      if [ -f "${ff}.fix" ]
      then
        cp "${ff}.fix"  $ff
        rm "${ff}.fix"
      else
        echo "fix for head table flags in ${ff} appears to have failed"
      fi
    done
  fi
  cd ../..
elif [ $outputType == "o" ]
then
  echo "Running fontmake to build static CFF instances"
  fontmake -o otf -i -m $des
  if [ $? -ne 0 ]
  then
    echo "fontmake failed"
    exit 1
  fi
  cd instance_otf
  if [ $fonttype == "italic" ]
  then
    for ff in "${familyname}*Italic.otf"
    do
      gftools fix-dsig --autofix $ff
	    psautohint $ff
    done
  else
    for ff in `find . -maxdepth 1 -name "${familyname}*.otf" -not -name "*Italic.otf"`
    do
      gftools fix-dsig --autofix $ff
      psautohint $ff
    done
  fi
  cd ..
else
  echo "Running fontmake to build variable font"
  fontmake -o variable -m $des
  if [ $? -ne 0 ]
  then
    echo "fontmake failed"
    exit 1
  fi
  cp "variable_ttf/${fontname}-VF.ttf" .
  echo "Checking for dsig table"
  gftools fix-dsig --autofix "${fontname}-VF.ttf"
  echo "Building STAT table and fixing name table"
  python mkstat.py $fonttype
  if [ $? -ne 0 ]
  then
    echo "Failed to build STAT table"
    exit 1
  else
    cp "${fontname}[GRAD,opsz,wght]-withSTAT.ttf" "${fontname}[GRAD,opsz,wght].ttf"
  fi
  #
  # Hinting section: if autohinting requested, check for existence of
  #     ttfautohint-vf and run it if available.
  # If autohinting not requested, run Xgridfit.
  # If either of these methods fails, user will be left with unhinted font
  #     ${fontname}[GRAD,opsz,wght].ttf".
  #
  if [ $autohint == 1 ]
  then
    if command -v ttfautohint-vf &> /dev/null
    then
      echo "Running ttfautohint-vf"
      ttfautohint-vf "${fontname}-VF.ttf" tmp-font.ttf
      gftools-fix-hinting.py tmp-font.ttf
      cp tmp-font.ttf.fix "${fontname}[GRAD,opsz,wght].ttf"
      rm tmp-font.ttf.fix
    else
      echo "ttfautohint-vf (the variable-font-enabled version of ttfautohint)"
      echo "is required to auto-hint a variable font."
    fi
  else
    cp "${fontname}-VF.ttf" "${fontname}[GRAD,opsz,wght].ttf"
    echo "Running Xgridfit"
    xgridfit -q "xgf/Elstob-${fonttype}-all.xgf"
    if [ $? -ne 0 ]
    then
      echo "Failed to hint with Xgridfit."
    else
      cp "${fontname}[GRAD,opsz,wght]-hinted.ttf" "${fontname}[GRAD,opsz,wght].ttf"
    fi
  fi
  if [ $createwoff == 1 ]
  then
    echo "Creating woff2 version"
    woff2_compress "${fontname}[GRAD,opsz,wght].ttf"
  fi
  echo "Cleaning up"
  rm -f ${fontname}-VF.ttf
  rm -f tmp-font.ttf
  rm -f "${fontname}[GRAD,opsz,wght]-withSTAT.ttf"
  rm -f "${fontname}[GRAD,opsz,wght]-hinted.ttf"
fi
