#!/bin/sh
# update-fonts-scale
# compiles fonts.scale files for X font directories
# see mkfontdir(1) for a description of the format of fonts.scale 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##*/}

# 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
    ETCDIR=/etc/X11/fonts/$1
  fi
  # confirm that the directories to be operated on exist
  for DIR in $XDIR $ETCDIR; do
    VALID=yes
    if [ ! -d $DIR ]; then
      warn "$DIR does not exist or is not a directory"
      VALID=
    fi
  done
  if [ -n "$VALID" ]; then
    # are there any files to process?
    if [ "$(echo $ETCDIR/*.scale)" != "$ETCDIR/*.scale" ]; then
      for file in $ETCDIR/*.scale; do
        # only write fonts to the .scale file that actually exist, so that
        # removed-but-not-purged scalable font packages do not register
        # nonexistent fonts; this has the desirable side effect that the count
        # at the top of the file is also omitted
        # XXX: this technique will be tricked into yielding false negatives if
        # the font filename has whitespace in it
        while read FILENAME FONTNAME; do
          if [ -f "$XDIR/$FILENAME" ]; then
            echo "$FILENAME $FONTNAME" >> $XDIR/fonts.scale.update-tmp
          fi
        done < $file
      done
      # write new scale file in case we are interrupted
      # write new count to top of file
      # cat and pipe to wc so wc doesn't spew the filename
      cat $XDIR/fonts.scale.update-tmp | wc -l | tr -d '[:blank:]' > $XDIR/fonts.scale.update-new
      cat $XDIR/fonts.scale.update-tmp >> $XDIR/fonts.scale.update-new
      mv $XDIR/fonts.scale.update-new $XDIR/fonts.scale
      rm $XDIR/fonts.scale.update-tmp
    else
      # no files to process, remove the one in the font dir
      rm -f $XDIR/fonts.scale
      # 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:
