#!/bin/sh

help()
{
  progname=`basename $0`
  echo 'Usage: $progname name [dpi mode] [destdir].'
  echo "Examples: $progname cmr10"
  echo "          $progname cmr10 720 ljfour"
  exit 1
}

warning()
{
  progname=`basename $0`
  echo "$progname: $@" >&2
}

: ${MAKETEXDIR=`kpsetool -v '$MAKETEXDIR'`}
export MAKETEXDIR

# Possible local customizations? (We need to read the file later again!)
test -r $MAKETEXDIR/maketex.site && . $MAKETEXDIR/maketex.site

NAME=$1
case $# in
1|2) DPI=${MT_DEF_BDPI-600}; MODE=${MT_DEF_MODE-ljfour}; DEST=$2;;
3|4) DPI=$2;  MODE=$3;    DEST=$4;;
*)   help;;
esac

set `kpsetool -v '$TEXMF $FONTNAME'`
TEXMF=$1; FONTNAME=$2

: ${MT_PKDESTDIR='$MT_DESTROOT/$MT_PKPART/$MT_MODE/$MT_NAMEPART'}
: ${MT_TFMDESTDIR='$MT_DESTROOT/$MT_TFMPART/$MT_NAMEPART'}
: ${MT_DESTROOT='$TEXMF/fonts'}
: ${MT_DEFAULT_NAMEPART=tmp}
: ${MT_PKPART='pk'}
: ${MT_TFMPART='tfm'}
: ${MT_TFMNAME='$NAME.tfm'}
: ${MT_PKNAME='$NAME.${DPI}pk'}

# MT_NAMEPART is harder.
if test -z "$MT_NAMEPART"; then
  # Nothing specified, so try to intuit the directory from the
  # fontname. First the special cases: either $NAME matches an entire
  # name in special.map, or it matches the abbreviation in
  # special.map and ends with a numeral (for the pointsize).
  # We (painfully) use only the minimal features in original awk.
  if test -r $FONTNAME/special.map; then
    MT_NAMEPART=`awk \
'{if ($1 == NAME || (substr (NAME, 1, length ($1)) == $1 \
                  && substr (NAME, length (NAME), 1) ~ /[0-9]/)) \
 { print $2 "/" $3; exit; }}' NAME=$NAME $FONTNAME/special.map`

    if test -z "$MT_NAMEPART"; then
      # Try the normal case. Source first.
      s_abbrev=`echo $NAME | sed 's/^\(.\).*$/\1/'`
      sourcedir=`awk '{ if ($1 == s_abbrev) { print $2; exit; }}' \
                 s_abbrev=$s_abbrev $FONTNAME/source.map`

      if test -n "$sourcedir"; then
        # We found the source. Try for the typeface.
        t_abbrev=`echo $NAME | cut -c 2-3`
        typefacedir=`awk '{ if ($1 == t_abbrev) { print $2; exit; }}' \
                     t_abbrev=$t_abbrev $FONTNAME/typeface.map`

        if test -n "$typefacedir"; then
          # Found everything.
          MT_NAMEPART=$sourcedir/$typefacedir

        else
          warning "Could not map typeface abbreviation $t_abbrev."
        fi
      else
        warning "Could not map source abbreviation $s_abbrev."
      fi
    fi
  fi
  if test -z "$MT_NAMEPART"; then
    # If we failed for whatever reason, default to a generic subdir.
    MT_NAMEPART=$MT_DEFAULT_NAMEPART
  fi
fi

case "$DEST" in
  "") ;;
  /*) MT_PKDESTDIR=$DEST;; # Absolute, explicit destdir => use it.
   *) MT_NAMEPART=$DEST;; # Relative destdir => append to the default.
esac

test -r $MAKETEXDIR/maketex.site && . $MAKETEXDIR/maketex.site

eval MT_MODE=$MODE
eval MT_PKPART=$MT_PKPART
eval MT_DESTROOT=$MT_DESTROOT
eval PKNAME=$MT_PKDESTDIR/$MT_PKNAME
eval TFMNAME=$MT_TFMDESTDIR/$MT_TFMNAME

echo $PKNAME $TFMNAME | sed 's@//*@/@g'
