#!/bin/sh

DIR_PERMS=1777
FILE_PERMS=444
from=""
MODE=""
OP="cp"
here=`pwd`

progname="`basename $0`"

getmode()
{
        mode=`egrep '(mode=|gsftopk)' ${1+"$@"} | sed -n 'H; $g; $s/^.*mode=\([a-zA-Z0-9()]*\).*$/\1/; $s/.*gsftopk.*/gsftopk/; $s/.*(//; s/).*//; $p' | grep '^[a-zA-Z0-9]*$'`
        echo $mode
}

while true ; do
	case "$1" in
	  -m)   DFT_MODE=$2 ; shift ; shift ;;
	  -d)	OP=mv ; shift ;;
	  *)	break ;;
	esac
done
ARGS=${1+"$@"}

if [ $# = 0 ] ; then
	echo >&2
	echo "Usage: $progname [ -d ] [ -m mode ] path ..." >&2
	echo >&2
	echo "Copy tfm and pk fonts from path into the $DESTROOT hierarchy." >&2
	echo "   -m default MetaFont mode for pk files if autodetection fails" >&2
	echo "   -d delete files after copying" >&2
	exit
fi

for i in `find $ARGS \( -name '*.*[0-9]pk' -o -name '*.pk' \) -print 2>/dev/null`
do
	MODE=`getmode $i`
	test -z "$MODE" && MODE=$DFT_MODE
	if [ -z "$MODE" ]; then
		echo "$progname: mode for $i not detected." >&2 ; continue
	fi
	dir=`echo $i | sed 's/^[^\/]*$/./; s/\/[^\/]*$//'`
	file=`basename $i`
	res=`echo $file | sed 's/.*\.//;s/pk//'`
	if test -z "$res"; then
		case "$dir" in
			/*) : ;;
			*)  dir=$here/$dir ;;
		esac
		res=`echo $dir | sed 's@.*/dpi\([0-9]*\).*@\1@'`
		base=`basename $file .pk`
	else
		base=`basename $file .${res}pk`
	fi
	set x `MakeTeXnames $base $res $MODE`
	file=`basename $2`
	DESTDIR=`echo $2 | sed 's/^[^\/]*$/./; s/\/[^\/]*$//'`

	test -f "$DESTDIR/$file" && rm -f "$DESTDIR/$file"

	MakeTeXmkdir "$DESTDIR"
	test -d $DESTDIR || continue

	$OP $i $DESTDIR/pktmp.$$ || continue

	mv -f $DESTDIR/pktmp.$$ $DESTDIR/$file || continue
	chmod $FILE_PERMS $DESTDIR/$file || continue
	echo "$DESTDIR/$file"
	append_db $DESTDIR $file
done

for i in `find $ARGS -name \*.tfm -print 2>/dev/null` ; do
	dir=`echo $i | sed 's/^[^\/]*$/./; s/\/[^\/]*$//'`
	file=`basename $i`
	base=`basename $file .tfm`
	set x `MakeTeXnames $base $res $MODE`
	DESTDIR=`echo $3 | sed 's/^[^\/]*$/./; s/\/[^\/]*$//'`
	file=`basename $3`

	test -f "$DESTDIR/$file" && rm -f "$DESTDIR/$file"

	MakeTeXmkdir "$DESTDIR"
	test -d $DESTDIR || continue                               

	$OP $i $DESTDIR/tfmtmp.$$ || continue

	mv -f $DESTDIR/tfmtmp.$$ $DESTDIR/$file || continue
	chmod $FILE_PERMS $DESTDIR/$file || continue
	echo "$DESTDIR/$file"
	append_db $DESTDIR $file
done
