#!/bin/bash

#
# A shell script to add APLX font entries to an X-windows font directory
#
# This is used to add lines to a "fonts.scale" file before performing 
# a "mkfontdir" to propagate the information to the "fonts.dir" file.
#
# e.g.:
#
#   add_scales.sh  fonts.scale.aplx  /usr/lib/X11/fonts/Type1/fonts.scale
#
# This script uses the utility "addfonts" to do the real work, and is
# really just a safe version of
#
#   addfonts  fonts.scale.aplx  /usr/lib/X11/fonts/Type1/fonts.scale
#
# which does some checks and backs up the destination file before it is
# changed
#
# See the man page for "mkfontdir" for more info
#


print_usage_and_exit() {
	echo ""
	echo "Usage:"
	echo "    $0 <aplx-scale-file> <font-directory-scale-file>"
	echo "         where <aplx-scale-file> is a text file containing the lines"
	echo "         to be added to <font-directory-scale-file>"
	echo "Example:"
	echo "    $0  fonts.scale.aplx  /usr/lib/X11/fonts/Type1/fonts.scale"
	echo ""
	exit -1
}


echo ""

# Got 2 args?
if [ $# != 2 ]; then
	print_usage_and_exit
fi

APL_FONT_INFO=$1
FONT_DIR_FILE=$2

FONT_DIR=$(dirname "$FONT_DIR_FILE")
FONT_FILE=$(basename "$FONT_DIR_FILE")


# Is first one really a readable file?
if [ ! -r "$APL_FONT_INFO" -o ! -f "$APL_FONT_INFO" ]; then
	echo "$APL_FONT_INFO is not a readable file?"
	print_usage_and_exit
fi


# Is second one in a real directory?
if [ ! -d "$FONT_DIR" ]; then
	echo "$FONT_DIR is not a directory?"
	print_usage_and_exit
fi


# Backup original font info file if any
if [ -f $FONT_DIR_FILE ]; then
	#echo "Saving original file \"$FONT_DIR_FILE\""
	#echo "as \"$FONT_DIR_FILE.aplx_save\""

	cp -f $FONT_DIR_FILE $FONT_DIR_FILE.aplx_save

	if [ $? != 0 ]; then
		echo ""
		echo "Error creating backup file"
		exit -1
	fi
else
	echo "The font directory $FONT_DIR does not contain a $FONT_FILE file."
	echo "Please ensure the directory is in the X-windows font path."
	echo ""
	echo "Creating new file \"$FONT_DIR_FILE\""
	echo "0" > $FONT_DIR_FILE

	if [ $? != 0 ]; then
		echo ""
		echo "Error creating \"$FONT_DIR_FILE\""
		exit -1
	fi
fi

# addfonts utility should be in the same directory as this script
THIS_DIR=$(dirname "$0")

# Add in new entries
$THIS_DIR/addfonts $APL_FONT_INFO $FONT_DIR_FILE

if [ $? != 0 ]; then
	echo "Error creating new font file"
	exit -1
fi

echo ""

exit 0
