#!/bin/sh

THISDIR=`dirname "$0"`
DIRNAME=`readlink -f "$THISDIR/.."`
PROGNAME=`basename "$0"`

UNIFONT='/usr/share/unifont/unifont.hex'

if [ "$1" = '--help' ] ; then
    cat 1>&2 <<EOF
Usage: $PROGNAME [ -q ]

Find font usage and generate the necessary binary font files. Currently, only
GNU Unifont is supported.

The optional -q argument indicates quiet execution, suppressing all output.

This script assumes that Unifont is installed in the following location:

$UNIFONT

The UNIFONT variable should be adjusted if this is not the case.
EOF
    exit 1
fi

# Detect quiet operation.

if [ "$1" = '-q' ] ; then
    QUIET="$1"
    shift 1
else
    QUIET=
fi

# Find all needed fonts and generate them.

for NEEDED in `find "$DIRNAME/pkg" -name '*.tff.needed'` ; do
    TARGETDIR=`dirname "$NEEDED"`
    FONTFILE=`basename "$NEEDED" .needed`
    FONTNAME=`basename "$FONTFILE" .tff`

    FONTPATH="$TARGETDIR/$FONTFILE"

    if [ -e "$FONTPATH" ] ; then
        if [ ! "$QUIET" ] ; then
            echo "Exists, not generated: $FONTPATH" 1>&2
        fi
        continue
    fi

    if [ "$FONTNAME" != 'unifont' ] ; then
        if [ ! "$QUIET" ] ; then
            echo "Unrecognised ($FONTNAME), not generated: $FONTPATH" 1>&2
        fi
        continue
    fi

    if [ ! "$QUIET" ] ; then
        echo "$FONTPATH"
    fi

    if ! "$THISDIR/readfont.py" "$UNIFONT" "$FONTPATH" ; then
        cat 1>&2 <<EOF

Font generation halted due to conversion problem. Please check the UNIFONT
variable in this script, located here:

$DIRNAME/$PROGNAME
EOF
        exit 1
    fi

done
