#!/bin/bash
# makefont - Font Builder
#
# Saber Rasetikerdar<saber.rastikerdar@gmail.com>, 2015-2019.
# Danial Behzadi<dani.behzi@ubuntu.com>, 2023.

set -e

if [ ! -f "build.conf" ]; then
    echo "build.conf not found!"
    exit 1
fi

source build.conf

SCRIPTDIR=`dirname "$0"`
TEMPDIR="${PWD}/font-output-temp"
SOURCEDIR="source"
LATINDIR="latin"
DISTDIR="out"
BUILDCMD="${SCRIPTDIR}"/build.py
LATINCOPYRIGHT="${LATINCOPYRIGHT}"

if [ ! -f "${BUILDCMD}" ]; then
    echo "BUILDCMD not found!"
    exit 1
fi

if [ ! -d "${SOURCEDIR}" ]; then
    echo "SOURCEDIR not found!"
    exit 1
fi

rm -rf "${TEMPDIR}"
mkdir -p "${TEMPDIR}"
mkdir "${TEMPDIR}"/build

if [ ! -d "${TEMPDIR}"/build ]; then
    echo "TEMPDIR/build not found!"
    exit 1
fi

# Make all the possible versions
for ((i=0;i<${#SOURCEFILES[@]};++i));
do
  sf="$SOURCEDIR"/"${SOURCEFILES[i]}"
  lf="${LATINDIR}"/"${LATINFILES[i]}"
  bn=$(basename ${sf})
  filename="${bn%.*}"
  if [ -f ${sf} ]; then
    python3 "${BUILDCMD}" --input="${sf}" --output="${TEMPDIR}"/build/$filename-WOL.ttf
    if [ -f ${lf} ]; then
      python3 "${BUILDCMD}" --input="${sf}" --latin="${lf}" \
	      --latin-copyright="${LATINCOPYRIGHT}" --output="${TEMPDIR}"/build/$filename.ttf
    fi
  fi
done

# Make all file types
for f in "${TEMPDIR}"/build/*.ttf
do
  if [ -f "${f}" ]; then
    fn=$(basename "${f}")
    ttfautohint -n -a qqs -W -D arab -f latn -G 11 -l 8 -r 11 "${f}" "${TEMPDIR}/${fn}"
  fi
done
rm -rf "${TEMPDIR}"/build

# Move files to where they belong to
mkdir "${TEMPDIR}"/Without-Latin
mv "${TEMPDIR}"/*WOL* "${TEMPDIR}"/Without-Latin

# Add other(license, readme, ...) files defined in build.conf
for ((i=0;i<${#ADDFILES[@]};++i));
do
  cp "${ADDFILES[i]}" "${TEMPDIR}"
done

# Make variable
if [ -d "variable" ]; then
  cd variable/
  . makevariable.sh "${TEMPDIR}"
  cd ..
fi

# Make folder "dist"
mkdir -p "${DISTDIR}"
cp -rf "${TEMPDIR}"/**/ "${DISTDIR}"
cp -rf "${TEMPDIR}"/*.ttf "${DISTDIR}"

# Clean up
rm -rf "${TEMPDIR}"
