#!/bin/bash

# 20170403 bkw:

# convert TTF (or OTF) fonts to *.psfu.gz fonts that can be used
# on the Linux console.

# conversion isn't done directly. instead, the TTF is rendered as a
# BDF (via otf2bdf), then converted to a psfu via bdf2psf.

# these are supposedly in points. yeah, right.
SIZES=${SIZES:-8 12 15 19}

warn() {
	echo "$@" 1>&2
}

die() {
	warn "$@"
	exit 1
}

convfont() {
	font="$1"
	file="$( fc-list "$font" | head -n1 | cut -d: -f1 )"

	psfname="$( basename "$( echo $file | cut -d. -f1 | tr A-Z a-z | tr -d " " )" )"
	echo -n "$file => $psfname: "

	if [ ! -e "$file" ]; then
		warn "Font '$font' not found, skipping"
		return 1
	fi

	for size in $SIZES; do
		echo -n "$size"
		sh ./ttf2psfu.sh -p $size "$file" &> $psfname.$size.log

		# bug in file? if the width is double-digit, file prints HxW, but if
		# width is single-digit it prints WxH, WTF?
		#pxsize=$( file test.psfu | sed 's|.*, \(.*\)x\(.*\)$|\2x\1|' )

		w="$( psf2txt test.psfu | sed -n '/^Width/s,.* ,,p' )"
		h="$( psf2txt test.psfu | sed -n '/^Height/s,.* ,,p' )"
		pxsize=${w}x${h}
		gzip -9c < test.psfu > $psfname-$pxsize.psfu.gz
		rm -f test.psfu
		echo -n ":$pxsize "
	done
	echo
}

cat fonts | while read font; do
	convfont "$font"
done
