#!/bin/sh
# update-fonts-dir
# compiles fonts.dir files for X font directories
# see mkfontdir(1) for a description of the format of fonts.dir files
# Copyright 1999,2001,2002 Branden Robinson.
# Licensed under the GNU General Public License, version 2.  See the file
# /usr/share/common-licenses/GPL or <http://www.gnu.org/copyleft/gpl.txt>.

PROGNAME=${0##*/}
ENCDIR=/usr/X11R6/lib/X11/fonts/encodings

# display a message, wrapping lines at the terminal width
message () {
  echo "$PROGNAME: $*" | fold -s -w ${COLUMNS:-80};
}

warn () {
  echo "$(message "warning: $*")" >&2;
}

error () {
  echo "$(message "error: $*")" >&2
  exit 1;
}

if [ $# -eq 0 ]; then
  error "one or more font directories must be provided"
fi

while [ -n "$1" ]; do
  # try to be clever about the arguments
  if expr "$1" : "/.*" > /dev/null 2>&1; then
    # absolute path to X font directory was provided
    XDIR=$1
    ETCDIR=/etc/X11/fonts/${XDIR##*/}
    if [ "$XDIR" = "$ETCDIR" ]; then
      # they gave us an /etc directory as the argument
      error "path to X font directory must be used"
    else
      warn "absolute path $XDIR was provided"
    fi
  else
    # assume they just gave us the basename
    XDIR=/usr/lib/X11/fonts/$1
  fi
  # confirm that the directories to be operated on exist
  VALID=yes
  if [ ! -d $XDIR ]; then
    warn "$XDIR does not exist or is not a directory"
    VALID=
  fi
  if [ -n "$VALID" ]; then
    if [ -d $ENCDIR -a -d $ENCDIR/large ]; then
      /usr/bin/X11/mkfontdir -e $ENCDIR -e $ENCDIR/large $XDIR
    else
      /usr/bin/X11/mkfontdir $XDIR
    fi
    # are there any fonts in the font dir?
    if [ "$(head -n 1 $XDIR/fonts.dir)" = "0" ]; then
      rm -f $XDIR/fonts.dir $XDIR/encodings.dir
      # remove the font dir if it is empty
      rmdir $XDIR > /dev/null 2>&1 || true
    fi
  fi
  shift
done

exit 0

# vim:ai:et:sts=2:sw=2:tw=0:
