#!/bin/sh
# original mktexpk -- make a new PK font, because one wasn't found.
# 
# (If you change or delete the word `original' on the previous line,
# installation won't write this script over yours.)
# 
# te@informatik.uni-hannover.de, kb@mail.tug.org, and infovore@xs4all.nl.
# Public domain.

gawkloc=`which gawk|grep ":"`
if test "$gawkloc" != ""; then
   gawkbin="awk"
else
   gawkbin="gawk"
fi

export $gawkbin

WORKDIR=`pwd`
version='$Id: mktexpk,v 1.21 1998/02/20 16:23:22 olaf Exp $'
progname=`echo $0 | sed 's%.*/%%'`
usage="Usage: $progname [OPTIONS] NAME [REDIRECT],
  Create a PK font.

--dpi DPI           use resolution DPI.
--bdpi BDPI         use base resolution BDPI.
--mag MAG           use magnificiation MAG.
--mfmode MODE       use MODE as the METAFONT mode.
--destdir DESTDIR   write fonts in DESTDIR.

Try to create a PK file for NAME at resolution DPI, with an assumed
device base resolution of BDPI, and a Metafont \`mag' of MAG. Use MODE
for the METAFONT mode.  Use DESTDIR for the root of where to install
into, either the absolute directory name to use (if it starts with a
/) or relative to the default DESTDIR (if not). REDIRECT, if supplied,
is a string of the form '>&n', where n is the number of the file
descriptor which is to receive, instead of stdout, the name of the
newly created pk file."

# provide defaults in case that no option is specified:

# Handle non-positional options, except for --version/--help
while test $# -gt 0; do
  case "$1" in
    --destdir) shift; DEST="$1"; shift ;;
    --destdir=*) DEST="`echo \"$1\" | sed 's/--destdir=//'`"; shift ;;
    --dpi) shift; DPI="$1"; shift ;;
    --dpi=*) DPI="`echo \"$1\" | sed 's/--dpi=//'`"; shift ;;
    --bdpi) shift; BDPI="$1"; shift ;;
    --bdpi=*) BDPI="`echo \"$1\" | sed 's/--bdpi=//'`"; shift ;;
    --mfmode) shift; test "x$1" != "x/" && MODE="$1"; shift ;;
    --mfmode=*) test "x$1" != "x--mfmode=/" \
        && MODE="`echo \"$1\" | sed 's/--mfmode=//'`"; shift ;;
    --mag) shift; MAG="$1"; shift;;
    --mag=*) MAG="`echo \"$1\" | sed 's/--mag=//'`"; shift ;;
    --version|-version) break ;;
    --help|-help) break ;;
    *) break ;;
  esac
done

if test "x$2" != x; then
  tail="`echo \"x$2\" | sed 's/^x>&//' | grep '^[0-9]*$'`"
  if test -z "$tail"; then
    echo "$progname: argument '$2' ignored - bad file number" >&2
  elif test "$tail" != 1; then
      eval 'exec 1>&$tail'
  fi
fi

mt_max_args=2

# Common code for all scripts.
: ${MT_TEXMFMAIN=`kpsewhich --expand-path='$TEXMFMAIN'`}
: ${MT_MKTEX_OPT=`kpsewhich --format='web2c files' mktex.opt`}
test -n "$MT_MKTEX_OPT" || MT_MKTEX_OPT="$MT_TEXMFMAIN/web2c/mktex.opt"
if test ! -f "$MT_MKTEX_OPT"; then
  echo "$progname: Cannot find mktex.opt; check your installation." >&2
  exit 1
fi

. "$MT_MKTEX_OPT"

: ${DPI=$BDPI}
: ${MAG=1.0}

# Since we want to pass the generated filename and only that filename
# back to the caller on standard output, we do some redirections so
# regular echo's will end up on stderr, and do an echo >$STDOUT at the end.
# Then the contents of $STDOUT will be echoed to stdout by a trap.

NAME=$1
ttfyes="0"

  ttfdir=$TEXMF/fonts/chinese/ttf
  ttfname=`echo $NAME|awk '{print substr($0,1,length($0)-2)}' -`

  echo "yes" > tmp@

#  $gawkbin -v ttfname=$ttfname '

  ttfnamenopbf=`
  $gawkbin  '
  BEGIN{}
  {if (index(ttfname,"_pfb") > 0) 
      {ttfnamenopbf=substr(ttfname,1,length(ttfname)-4)
       print ttfnamenopbf}
   else
      {print ttfname}
   }
  END{}' ttfname=$ttfname tmp@ `

  if test "$ttfname" != "$ttfnamenopbf"; then 
     pfbfile="y"
  fi
  if test "$pfbfile" = "y"; then
    if test ! -s $WORKDIR/runno@; then
     echo "yes" > $WORKDIR/runno@
     echo "                                           " 1>&2 
     echo "  You have used chinese Adobe type font:   " 1>&2
     echo "      $ttfname                             " 1>&2
     echo "  Using xdvi may not have reqiured result. " 1>&2
     echo "  You had better use                       " 1>&2
     echo "     'dvips' and 'ghostview/gv'            " 1>&2
     echo "  or use                                   " 1>&2
     echo "      'chitexpsv'                          " 1>&2
     echo "  instead.                                 " 1>&2
     echo "                                           " 1>&2
     echo "  Press enter key to continue or/and type 'Ctrl C'" 1>&2    
     echo "  to quit any time."  1>&2
     read xxyyzz
    fi
 fi


# start of redirection stdout -> stderr, stdin <- /dev/null
(

NAME=$1
ttfyes="0"

  ttfdir=$TEXMF/fonts/chinese/ttf
  if test -r $ttfdir/`echo $NAME|awk '{print substr($0,1,length($0)-2)}' -`.ttf -o \
       -r $ttfdir/`echo $NAME|awk '{print substr($0,1,length($0)-2)}' -`.ttc; then
     ttfname=`echo $NAME|awk '{print substr($0,1,length($0)-2)}' -`
     ttfyes="1"
  fi


# grep for the font in $PSMAPFILE.  These are base font names, such as
# rpplr (the original) or pplr0 (an interim step) or pplr8r (current).
: ${PSMAPFILE=`kpsewhich psfonts.map`}
pattern="^$NAME"'([ 	]|$)' 
psline=`egrep "$pattern" "$PSMAPFILE" 2>/dev/null`

if test -n "$psline"; then
  MODE=modeless
  # ps_to_pk is set in mktex.opt
  case $ps_to_pk in
    ps2pk)
      set x `echo "$psline" | sed 's%[<["]%%g'`
      shift; shift; shift;
      encoding=; psname=; slant=; extend=
      while test ! -z "$1"; do
        case "$1" in
          *.enc)       encoding="-e $1";;
          *.pf[ab])    psname="$1";;
          *SlantFont)  slant="-S $lastopt";;
          *ExtendFont) extend="-E $lastopt";;
        esac
        lastopt="$1"
        shift
      done
      test -n "$psname" ||
        { pfa=`(kpsewhich $NAME.pfa 2>/dev/null)`; psname=$pfa; }
      test -n "$psname" ||
        { pfb=`(kpsewhich $NAME.pfb 2>/dev/null)`; psname=$pfb; }
      ANAME=`echo $NAME | sed 's/8r$/8a/'`
      test -n "$psname" ||
        { pfa=`(kpsewhich $ANAME.pfa 2>/dev/null)`; psname=$pfa; }
      test -n "$psname" ||
        { pfb=`(kpsewhich $ANAME.pfb 2>/dev/null)`; psname=$pfb; }
      if [ -z "$psname" ]; then
        echo "$progname: cannot find $NAME.pfa or $NAME.pfb. Trying gsftopk." >&2
#        cmd="ps2pk -v -X$DPI -R$BDPI $slant $extend $encoding $psname $NAME.${DPI}pk"
        cmd="gsftopk $NAME $DPI"
        # make sure that gsftopk uses the psline from out mapfile:
        echo "$psline" > psfonts.map
        TEXFONTMAPS=.:$TEXFONTMAPS
      else
        cmd="ps2pk -v -X$DPI -R$BDPI $slant $extend $encoding $psname $NAME.${DPI}pk"
      fi
      ;;
    *)
      WU=`
      $gawkbin '
      BEGIN{}
      {ch=substr(name,1,1)
       chh=substr(name,1,2)   
       chb=substr(name,2,1)
       chhb=substr(name,3,1)
       chfthr=substr(name,1,3)
       chfour=substr(name,4,1)
       chfive=substr(name,5,1)
       if ((ch=="m"||ch=="f") && chb >=0 && chb<=9)
          {print "m"}
       if ((chh=="bb") && chhb >=0 && chhb<=9)
          {print "m"}
       if ((chfthr=="ntu") &&
          (chfour=="k"||chfour=="f"||chfour=="l"||chfour=="r" ) \
           && (chfive >=0 && chfive<=9)) 
          {print "m"}
       if ((chfthr=="moe") &&
          (chfour=="k"||chfour=="s") && (chfive >=0 && chfive<=9)) 
          {print "m"}
      }
      END{} ' name=$NAME tmp@ `
     
      if test "$WU" != "m"; then
         cmd="$ps_to_pk $NAME $DPI" 
      else
         cmd="ps2pk -v -X$DPI -R$BDPI $slant $extend $encoding $psname $NAME $NAME.${DPI}pk"
      fi

      ;;
  esac
elif (ttf2pk -t -q $NAME) >/dev/null 2>&1; then
  MODE=modeless
  cmd="ttf2pk -q $NAME $DPI"
elif (hbf2gf -t -q $NAME) >/dev/null 2>&1; then
  MODE=modeless
  cmd="hbf2gf -q -p $NAME $DPI"
else
  # Check that $BDPI and $MODE are consistent; if not, ignore the mode and
  # hope we can correctly guess it from bdpi.  (People like to specify the
  # resolution on the command line, not the mode so much.)
  if test -n "$MODE"; then
    mf_bdpi=`mf \
'\mode:='$MODE';mode_setup;message"BDPI= "&decimal round pixels_per_inch;end.'\
             </dev/null \
             | awk '/DPI=/ {print $2}'`
    if test "x$mf_bdpi" != x$BDPI; then
     if test "$ttfyes" != "1"; then
      echo "$progname: Mismatched mode $MODE and resolution $BDPI; ignoring mode." >&2
     fi
      MODE=
    fi
  fi

  # If an explicit mode is not supplied, try to guess. You can get a
  # list of extant modes from ftp://ftp.tug.org/tex/modes.mf.
  if test -z "$MODE" || test "x$MODE" = xdefault; then
    case "$BDPI" in
      85) MODE=sun;;
     100) MODE=nextscrn;;
     180) MODE=toshiba;;
     300) MODE=cx;;
     400) MODE=nexthi;;
     600) MODE=ljfour;;
    1270) MODE=linoone;;
       *) echo "$progname: Can't guess mode for $BDPI dpi devices." >&2
          echo "$progname: Use a config file, or update me." >&2
          exit 1
    esac
  fi

  # Run Metafont. Always use plain Metafont, since reading cmbase.mf
  # does not noticeably slow things down.

  
#  ttfdir=$TEXMF/fonts/chinese/ttf
#  if test -r $ttfdir/`echo $NAME|sed -e 's/[0-9][0-9]$//'`.ttf -o \
#       -r $ttfdir/`echo $NAME|sed -e 's/[0-9][0-9]$//'`.ttc; then
#     ttfname=`echo $NAME|awk '{print substr($0,1,length($0)-2)}' -`
#     ttfyes="1"

   if test "$ttfyes" = "1"; then

     # test for TTF fonts

     ttf2pk -q $NAME $DPI > nul
     errstatus=$?
     if test $errstatus -ne 2; then
      if test $errstatus -ne 0; then
        echo "$progname: \`ttf2pk' failed." >&2
        exit 1
      fi
       MODE=modeless
#      MODE=ttf2pk		# preferred mode for TDS would be `modeless'
#      MODE=ljfour		# preferred mode for TDS would be `modeless'
      psline=ttf2pk		# a dummy value to prevent a call to gftopk later
      cmd=true

     fi
  else
    cmd="mf \mode:=$MODE; mag:=$MAG; nonstopmode; input $NAME"
#  cmd="mf \mode:=$MODE; mag:=$MAG; nonstopmode; input $NAME"
 fi
fi

OIFS=$IFS; IFS=$SEP
set x `"$MT_MKTEXNAM" $NAME $DPI $MODE $DEST`; shift
IFS=$OIFS

PKDEST="$1"
PKDESTDIR=`echo "$PKDEST" | sed 's%/[^/][^/]*$%%'` # can't rely on dirname
PKNAME=`basename "$PKDEST"`
GFNAME=$NAME.${DPI}gf

if test -r "$PKDESTDIR/$PKNAME"; then
  echo "$progname: $PKDESTDIR/$PKNAME already exists." >&2
  echo "$PKDESTDIR/$PKNAME" >$STDOUT
  "$MT_MKTEXUPD" "$PKDESTDIR" $PKNAME
  exit 0
fi

"$MT_MKTEXDIR" "$PKDESTDIR"
if test ! -d "$PKDESTDIR"; then
  echo "$progname: mktexdir $PKDESTDIR failed." >&2
  exit 1
fi

#echo "$progname: Running $cmd"
$cmd </dev/null || {
  # Don't abort if only "Strange path" errors occurr.
  grep '^!' $NAME.log >$$.errs 2>/dev/null
  grep '^! Strange path' $$.errs >$$.strange 2>/dev/null
  if cmp $$.errs $$.strange >/dev/null 2>&1 \
    && test -s $$.strange >/dev/null 2>&1; then
    echo "$progname: warning: \`$cmd' caused strange path errors." >&2
  else
    echo "$progname: \`$cmd' failed." >&2
    test -s $NAME.log && mv -f $NAME.log "$KPSE_DOT"
    exit 1;
  fi
}

test -r $GFNAME && { gftopk ./$GFNAME $PKNAME || exit 1; }
test ! -f $PKNAME && test -f $NAME.${DPI}pk && mv $NAME.${DPI}pk $PKNAME
if test ! -s $PKNAME; then
  echo "$progname: \`$cmd' failed to make $PKNAME." >&2
  exit 1
fi

# Install the PK file carefully, since others may be working simultaneously.
# Use cp when mv fails, since DOS will fail mv for deeply-nested directories.
mv $PKNAME "$PKDESTDIR/pk$$.tmp" 2>/dev/null \
  || cp $PKNAME "$PKDESTDIR/pk$$.tmp" || exit 1
cd $PKDESTDIR || exit 1
chmod `kpsestat -xst,go-w .` pk$$.tmp
test -r $PKNAME || mv pk$$.tmp $PKNAME || exit 1

# Update ls-R if necessary.
"$MT_MKTEXUPD" "$PKDESTDIR" $PKNAME

# If this line (or an equivalent) is not present, dvipsk/xdvik/dviljk
# will think mktexpk failed.  Any other output to stdout will also lose.
echo "$PKDESTDIR/$PKNAME" >$STDOUT
echo "$progname: $PKDESTDIR/$PKNAME: successfully generated." >&2
) 1>&2 </dev/null
