#!/bin/sh

# Install the BDF fonts where they belong. DESTDIR, BDFDIR, and TTFDIR
# must be given as arguments. If DESTDIR is blank, the X server and
# fontconfig will be informed about the new fonts. If DESTDIR is NOT
# blank, we're not really installing the fonts system-wide, so no
# extra config will be done (the files will just be copied).

DESTDIR="$1"
BDFDIR="$2"
TTFDIR="$3"

SYSTEM=yes

if [ "$DISPLAY" = "" ]; then
	SYSTEM=no
fi

if [ "$DESTDIR" != "" ]; then
	BDFDIR="$DESTDIR/$BDFDIR"
	TTFDIR="$DESTDIR/$TTFDIR"
	SYSTEM=no
fi

if [ "$#" != "3" -o "$BDFDIR" = "" ]; then
	echo "usage: $0 <destdir> <bdfdir> <ttfdir>"
	exit 1
fi

echo -n "$0: will "
if [ "$SYSTEM" != "yes" ]; then
	echo -n "NOT "
fi
echo "run mkfontdir/mkfontscale/xset/fc-cache"

install_font() {
	BDF=fauxtari-$1.bdf
	ALIAS=fauxtari-$1
	cp "fonts/$BDF" "$BDFDIR"
	chown root:root "$BDFDIR/$BDF" &> /dev/null
	if [ "$SYSTEM" = "yes" ]; then
		( cd "$BDFDIR"
		  mkfontdir
		  mkfontscale
		  if ! grep "^$ALIAS" fonts.alias &> /dev/null; then
			  NAME="$( grep "^$BDF" fonts.dir | cut -d' ' -f2- )"
			  echo "$ALIAS \"$NAME\"" >> fonts.alias
		  fi
		)
	fi
}

mkdir -p "$BDFDIR" || exit 1
mkdir -p "$TTFDIR" || exit 1
install_font 8
install_font 16
install_font 24

cp "fonts/FauxtariScalableMono.ttf" "$TTFDIR"
if [ "$SYSTEM" = "yes" ]; then
	fc-cache -f "$BDFDIR" &> /dev/null
	xset fp rehash &> /dev/null
	if [ "$BDFDIR" != "$TTFDIR" ]; then
		cd "$TTFDIR"
		mkfontdir
		mkfontscale
		fc-cache -f "$TTFDIR" &> /dev/null
	fi
fi
