#!/bin/sh

PROG="${0##*/}"

XFS=
USEXFS=0
XSET=
ADD=0
FONTPATH=
CHKFONTPATH=

Usage()
{
	[ "$1" = 0 ] || exec >&2
	cat <<EOF
Usage: $PROG option[s] directory

Valid options are:
-a, --add=DIRECTORY		Add directory to font path
-r, --remove=DIRECTORY		Remove directory from font path
-f, --first			Make --add to put the directory first (not last)
				in the path
EOF

	[ -n "$1" ] && exit "$1" || exit
}

[ -n "$*" ] || Usage

TEMP=`getopt -n "$PROG" -o a:r:f -l add:,remove:,first -- "$@"` || Usage
eval set -- "$TEMP"

if [ -r /etc/sysconfig/xfs ]; then
	source /etc/sysconfig/xfs
		case "$XFS" in
			yes|Yes|YES|true|True|TRUE|on|On|ON|Y|y|1)
				USEXFS=1
		;;
		esac
fi

while :; do
	case "$1" in
		-a|--add)
			shift
			[ -n "$XSET" ] || XSET="fp+"
			ADD=1
			[ -n "$CHKFONTPATH" ] || CHKFONTPATH="-q -a"
			FONTPATH="$1"
			shift
		;;
		-r|--remove)
			shift
			XSET="-fp"
			ADD=0
			CHKFONTPATH="-q -r"
			FONTPATH="$1"
			shift
		;;
		-f|--first)
			XSET="+fp"
			ADD=1
			CHKFONTPATH="-q -fa"
			shift
		;;
		--)
			shift
			break
		;;
	esac
done

eval /usr/sbin/chkfontpath "$CHKFONTPATH" "$FONTPATH" >/dev/null 2>&1

if [ "$USEXFS" = 0 ]; then
	XPID=`pidof X`
	if [ -n "$XPID" ]; then
		for n in $XPID; do
			SERVER=`awk -F: '{print(substr($2,1,1))}' /proc/$n/cmdline`
			[ -n "$SERVER" ] || continue
			AUTH=`awk -F-auth '{print($2)}' /proc/$n/cmdline`
			[ -r "$AUTH" ] || continue
			export XAUTHORITY="$AUTH"
			FP=`xset -display :"$SERVER" q | grep -q "$FONTPATH"; echo $?`
			if [ "$FP" = 1 -o "$ADD" = 0 ]; then
				xset -display :"$SERVER" "$XSET" "$FONTPATH" > /dev/null 2>&1
			fi
			xdpyinfo -display :"$SERVER" | grep -q FontCache &&
				xset -display :"$SERVER" fp rehash
		done
	fi
fi
