#!/bin/sh
#
# translatepcfonts [[-l] | [-d destdir]] [-s sourcedir [sourcedir ...] ]
#
# This script translates a font from the IBM PC .PFB format to the SGI format.
#
# The font files are assumed to have the same base name with differing
# suffixes, and are assumed to exist in the current directory, unless
# the -s <sourcedir> argument is given, in which case <sourcedir> is
# searched for the font files.  If the -s option is given, it must be
# last on the command line, as all subsequent arguments are taken to
# be source directories.
#
# The proper font file suffixes are .PFB for the binary outline file, 
# and .AFM for the ASCII AFM file. 
#
# The -d <destdir> option may be given to specify a base directory.
# >> NOTE: the directories <destdir>/outline/base and <destdir>/AFM
# >> are the directories into which fonts are actually installed.
#

PrintUsageMessage()
# 
# echoes usage message to stdout
#
{
   echo "USAGE: $progname [-s sourcedir] [-d destdir]"
   echo ""
   echo "To translate fonts in place, simply specify the source directory."
   echo "If no source directory is specified, the current dir is used."
   echo ""
   echo "To specify an install directory, specify '-d destdir'"
   echo "Note that the fonts are actually installed into the directories"
   echo " <destdir>/outline/base and <destdir>/AFM."
   echo ""
   echo "To list the names of the fonts in the source directory,"
   echo "use the '-l' option."
   echo ""
   echo "NOTE: You must be root to run this program with the '-d' option."
   echo ""
}


VerifyUserIsRoot()
#
# Checks that we are the super-user.
#
{
    cid=`/usr/bin/id | /usr/bin/awk '{print substr($1,index($1,"("))}'`;
    if [ "$cid" != "(root)" ]; then
        echo ""
        echo "ERROR: You must be logged in as root"
	echo "       to use this program to install fonts."
	echo ""
	echo "(If you don't have root permissions, "
	echo " translate locally and then copy by hand"
	echo " into your destination directory.)"
	echo ""
        exit 1;
    fi
}

VerifyInstallDirectoriesExist()
#
# Checks that the directories into which we are to install exists:
# Expects as its first argument the base directory to test.
#
{ 
  if [ $# -ne 1 ]; then
     echo "ERROR: invalid number of args to subroutine, exiting."
     return 2
  fi
  DIR=$1
  if [ ! -d $DIR/outline/base ]; then
     echo "$progname: Unable to install: Font directory $DIR/outline not found."
     exit 1
  fi
  if [ ! -d $DIR/AFM ]; then
     echo "$progname: Unable to install: AFM directory $DIR/AFM not found."
     exit 1
  fi
}


ListFontsInDirectory()
#
# Fetches a list of fonts in the sourcedir and reports them on stdout
# Expects the temporary directory as argument 1.
{
  if [ $# -ne 1 ]; then
     echo "ERROR: invalid number of args to subroutine, exiting."
     return 2
  fi
  TMP=$1

  echo "Fonts Available:    (Please wait while I fetch list...)"
  echo ""
  for file in $SRCDIR/*.PFB; do
     # Grab the PostScript fontname out of the file
     FONTNAME=`/usr/bin/egrep '/FontName [^ ]* def' $file | \
               /bin/sed -e 's#^.*/FontName[ (/]*\([^ )]*\)[) ]*def.*$#\1#'`
     echo "$FONTNAME"
  done
  echo ""
  echo "Done."
}


InstallFontFromSourceDir()
#
# Performs font installation.
# First Arg : file path to original file
# Second Arg: base filename of original font file, less any suffix.
# Third Arg : destination directory for DPS, to which
#		/outline/base is added for outlines, and
# 		/AFM is added for font metric files.
# Fourth Arg: the font name, as known to DPS.
#
{
  if [ $# -ne 4 ]; then
     echo "ERROR: invalid number of args to subroutine, exiting."
     return 2
  fi
  SRCDIR=$1
  SRCNAME=$2
  DESTDIR=$3
  FONTNAME=$4

  # Now move the PS and AFM files to the proper places for DPS:
  /bin/mv $SRCDIR/$FONTNAME $DESTDIR/outline/base/$FONTNAME
  mverror1=$?
  /bin/mv $SRCDIR/$FONTNAME.AFM $DESTDIR/AFM/$FONTNAME
  mverror2=$?

  if [ $mverror1 != 0 -o $mverror2 != 0 ]; then
     echo "ERROR while copying outline and AFM files to $DESTDIR"
     /bin/rm -f $DESTDIR/outline/base/$FONTNAME
     /bin/rm -f $DESTDIR/AFM/$FONTNAME
     return 1
  fi
 
  # Now merge the temporary XLFD file with the existing file, if any.
  # Remove duplicates and save only unique entries.
  sort -T $TMPDIR -u -o $GLOBAL_XLFD $GLOBAL_XLFD $TMP_XLFD
  if [ $? != 0 ]; then
     echo "WARNING: Could not update X font table!"
     echo "         Your new fonts may not appear in the X font database."
     /bin/rm -f $TMP_XLFD
     return 1
  fi
  /bin/rm -f $TMP_XLFD

  return 0
}

CreateXLFDFromAFMFile()
#
# Creates an XLFD given an AFM file.
# First Arg : file path to original AFM file
# Second Arg: PostScript font name
# Returns:    a single text line suitable for inclusion in an XLFD map file.
#
{
  afmfile=$1
  fontname=$2

  # Take the full family name as the family:
  family=`fgrep FamilyName $afmfile | cut -d" " -f2-`

  # Take just the first word of the weight entry:
  # (The rest of the line is used for width.)
  fileWeight=`fgrep Weight $afmfile`
  weight=`echo $fileWeight | cut -d" " -f2`
  if [ -z "$weight" ]; then
     weight="r"
  fi

  # Look for {Italic,Oblique} in the full font name:
  fullname=`fgrep FullName $afmfile`
  slant="r" # assume roman unless proven otherwise
  echo "$fullname" | fgrep -s Italic
  if [ $? = 0 ]; then
     slant="i"
  else
      echo "$fullname" | fgrep -s Oblique
      if [ $? = 0 ]; then
         slant="o"
      fi
  fi

  width="normal" # assume normal unless proven otherwise
  # look for {Ultra,Extra}{Condensed,Compressed,Narrow}
  echo "$fileWeight" | fgrep -s Ultra
  if [ $? = 0 ]; then
     width="ultra"
  else
      echo "$fileWeight" | fgrep -s Extra
      if [ $? = 0 ]; then
         width="extra"
      fi
  fi
  # If there is more than one of {Condensed,Compressed,Narrow},
  # then only one will show up.  This appears a reasonable assumption.
  echo "$fileWeight" | fgrep -s Condensed
  if [ $? = 0 ]; then
     width="${width}Condensed"
  fi
  echo "$fileWeight" | fgrep -s Compressed
  if [ $? = 0 ]; then
     width="${width}Compressed"
  fi
  echo "$fileWeight" | fgrep -s Narrow
  if [ $? = 0 ]; then
     width="${width}Narrow"
  fi

  spacing="p"  # Assume proportional unless proven otherwise.
  fileSpacing=`fgrep IsFixedPitch $afmfile | cut -d" " -f2`
  if [ "$fileSpacing" = "True" ]; then
     spacing="m"
  fi

  encoding=`fgrep EncodingScheme $afmfile | cut -d" " -f2-`
  if [ "$encoding" = "FontSpecific" ]; then
     encoding="adobe-fontspecific"
  elif [ "$encoding" = "AdobeStandardEncoding" ]; then
     encoding="iso8859-1"
  else
     return 1
  fi

  xlfd="-adobe-$family-$weight-$slant-$width--0-0-0-0-$spacing-0-$encoding"
  # Convert to all lower case
  xlfd=`echo $xlfd | tr "[A-Z]" "[a-z]"`

  # put 10 spaces between the two to match the standard ps2xlfd_map entries.
  echo "$fontname          $xlfd" >> $TMP_XLFD

  return 0
}

#
#  End of convenience routines, now do the work:
# 

verbose=0
progname=`basename $0`
SRCDIR=.
DESTDIR=/usr/lib/DPS

if [ "$TMPDIR" = "" ]; then
   TMPDIR=/var/tmp
fi

# Names of the ps2xlfd_map files, the main and the temporary files.
GLOBAL_XLFD=/usr/lib/X11/fonts/ps2xlfd_map.typeoncall
if [ ! -f $GLOBAL_XLFD ]; then
   cat /dev/null > $GLOBAL_XLFD
fi
TMP_XLFD=$TMPDIR/ps2xlfd_map.typeoncall
cat /dev/null > $TMP_XLFD

# Where to find the font utilities
UTILPATH=/usr/sbin

# Keep track of fonts successfully and unsuccessfully installed:
INSTALLFONTS=0 # Do not install into destdir by default.
badfonts=""
numbadfonts=0
goodfonts=""
numgoodfonts=0

# Get command line arguments:
#
while getopts "s:d:lv" c
do
	case $c in
	v ) 
	  verbose=1
	  ;;
	l ) 
	  ListFontsInDirectory $TMPDIR
	  exit $?
	  ;;
	d ) 
	  VerifyUserIsRoot
	  if [ -d $OPTARG ]; then
  	     DESTDIR=$OPTARG
	     if [ $verbose != 0 ]; then
                 echo "Fonts will be installed into base directory '$OPTARG'."
	     fi
	     INSTALLFONTS=1
	  else
	     echo "ERROR: '$OPTARG' is not a directory!  Using '$DESTDIR' instead."
	  fi
	  ;;
	s ) 
	  if [ -d $OPTARG ]; then
  	     SRCDIR=$OPTARG
	     if [ $verbose != 0 ]; then
	        echo "Fonts will be searched for in directory '$SRCDIR'."
	     fi
	  else
	     echo "ERROR: '$OPTARG' is not a directory!  Using '$SRCDIR' instead."
	  fi
	  ;;
        \?)
	  echo "(Type '$progname' alone to get a usage message)"
	  ;;
	esac
done
shift `expr $OPTIND - 1`

# First things first: verify that proper subdirs of DESTDIR exist
VerifyInstallDirectoriesExist $DESTDIR

for file in `find $SRCDIR -name \*.PFB -print`
do
    filedir=`dirname $file`
    basefilename=`basename $file`
    basefilename=`echo $basefilename | /bin/sed -e 's/\.PFB//'`

    # Grab the PostScript fontname out of the file
    fontname=`/usr/bin/egrep '/FontName [^ ]* def' $file |\
              /bin/sed -e 's#^.*/FontName[ (/]*\([^ )]*\)[) ]*def.*$#\1#'`
    echo "Translating font '$fontname'...."\\c

    # Convert binary PC format outline to DPS ASCII format outline
    $UTILPATH/pfb2pfa $file $filedir/$fontname
    # Convert the AFM from DOS to UNIX text format
    /usr/sbin/to_unix $filedir/$basefilename.AFM $filedir/$fontname.AFM
    
    if [ $? != 0 ]; then
       echo "failed!"
       echo "Outline translation failed!"
       numbadfonts=`expr $numbadfonts + 1`
       badfonts="$badfonts $fontname"
       continue;
    fi

    if [ $INSTALLFONTS != 0 ]; then
       CreateXLFDFromAFMFile $filedir/$fontname.AFM $fontname
    fi
    if [ $? != 0 ]; then
       echo "failed!"
       echo "Font file installation failed: XLFD could not be created."
       numbadfonts=`expr $numbadfonts + 1`
       badfonts="$badfonts $fontname"
       continue;
    fi

    if [ $INSTALLFONTS != 0 ]; then
       InstallFontFromSourceDir $filedir $basefilename $DESTDIR $fontname
    fi
    if [ $? != 0 ]; then
       echo "failed!"
       echo "Font file installation failed during file move!"
       numbadfonts=`expr $numbadfonts + 1`
       badfonts="$badfonts $fontname"
       continue;
    fi

    echo "done."
    numgoodfonts=`expr $numgoodfonts + 1`
    goodfonts="$goodfonts $fontname"
done

if [ $numbadfonts != 0 ]; then
   echo ""
   echo "Could not install the following fonts:"
   echo ""
   for i in $badfonts
   do
      echo "*> $i"
   done
fi
