#!/bin/ksh93

VERSION='$Id: mktextfm 34656 2014-07-18 23:38:50Z karl $'
typeset -r FPROG=${.sh.file}
typeset -r PROG=${FPROG##*/}
SDIR=${FPROG%/*}

# preferentially use subprograms from our own directory.
PATH="${SDIR}:${PATH}"
[[ ${ uname -s ; } == 'SunOS' ]] && GREP='/usr/xpg4/bin/grep' || GREP='grep'

function showUsage {
	[[ -z $1 ]] && X='--man' || X='-?'
	getopts -a ${PROG} "${ print ${USAGE} ; }" OPT $X
}

typeset -x MT_TEXMFMAIN KPSE_DOT		# cache its value globally
[[ -z ${KPSE_DOT} ]] && KPSE_DOT="${PWD}"
TDIR=

function cleanup {
	cd
	[[ -n ${TDIR} && -d ${TDIR} ]] && rm -rf ${TDIR}
}

function getTexMake {
	typeset -n VAR=$2
	[[ -n ${VAR} ]] && return 0

	[[ -z ${MT_TEXMFMAIN} ]] && \
		MT_TEXMFMAIN=${ kpsewhich --expand-path='$TEXMFMAIN' ; }
	typeset WHAT=
	case "$1" in
		name)	WHAT='mktexnam' ;;
		update)	WHAT='mktexupd' ;;
		dir)	WHAT='mktexdir' ;;
		*) return 1 
	esac

	VAR=${ kpsewhich --format='web2c files' ${WHAT} ; }
	[[ -z ${VAR} ]] && VAR="${MT_TEXMFMAIN}/web2c/${WHAT}"
	return 0
}

function doMain {
	[[ -z $1 ]] && showUsage 1 && exit 1

	# Where do potential driver files belong?
	[[ -z ${MT_MFDESTDIR} && \
		-n ${MT_FEATURES} && ${MT_FEATURES} == *nomfdrivers* ]] && \
		export MT_MFDESTDIR="${PWD}"

	typeset NAME="${1##*/}" DPI=${BDPI} X MAG=1  # mag=0 fails with larm1000.mf
	NAME="${NAME%.tfm}"

	typeset -x MT_MKTEXNAM MT_MKTEXUPD MT_MKTEXDIR
	getTexMake name MT_MKTEXNAM
	getTexMake update MT_MKTEXUPD

	X=${ "${MT_MKTEXNAM}" "${NAME}" ${DPI} "${MODE}" "${DEST}" ; }
	A=( ${X//:/ } )

	typeset PKDEST=${A[0]} TFMDEST=${A[1]} PKDESTDIR=${PKDEST%/*} \
		PKNAME=${.sh.match:1} TFMDESTDIR=${TFMDEST%/*} TFMNAME="${NAME}.tfm" \
		GFNAME="${NAME}.${DPI}gf" MF

	if [[ -r ${TFMDESTDIR}/${TFMNAME} ]]; then
		print -u2 "${PROG}: ${TFMDESTDIR}/${TFMNAME} already exists."
		print "${TFMDESTDIR}/${TFMNAME}"
		"${MT_MKTEXUPD}" ${TFMDESTDIR} "${TFMNAME}" 1>&2
		return $?
	fi

	TDIR=${ mktemp -t -d ${PROG}.XXXXXX ; }
	[[ -z ${TDIR} ]] && return 1

	# Try to create the destdir first. Do not create fonts, if this fails.
	"${MT_MKTEXDIR}" ${TFMDESTDIR} 1>&2
	if [[ ! -d ${TFMDESTDIR} ]]; then
		print -u2 "${PROG}: ${MT_MKTEXDIR##*/} '${TFMDESTDIR}' failed."
		return 1
	fi

	# Check if this font is supported by hbf2gf else use metafont.
	if hbf2gf -q -t "${NAME}" >/dev/null 2>&1 ; then
		CMD=( 'hbf2gf' '-g' "${NAME}" ${DPI} )
	else
		# determine the progname of metafont to use; prefer mf-nowin.
		MF=${ whence mf-nowin ; }
		[[ -z ${MF} ]] && MF='mf'
		CMD=("${MF}" "\mode:=${MODE}; mag:=${MAG}; nonstopmode; input ${NAME}")
	fi

	print -u2 "${PROG}: Running ${CMD[@]}"
	if ! "${CMD[@]}" 1>&2 </dev/null ; then
		# Don't abort if only "Strange path", "bad pos" or "angle(0,0)"
		# errors occurr.
		if [[ -s ${NAME}.log ]]; then
			[[ ${PWD} == "${KPSE_DOT}" ]] || \
				cp -f "${NAME}.log" "${KPSE_DOT}/" 2>/dev/null
			${GREP} '^!' "${NAME}.log" | sort >${TDIR}/errs 2>/dev/null
			${GREP} '^! Strange path' ${TDIR}/errs >${TDIR}/strange 2>/dev/null
			${GREP} '^! bad pos.' ${TDIR}/errs >${TDIR}/badpos 2>/dev/null
			${GREP} '^! angle(0,0) is taken as zero.' ${TDIR}/errs \
				>${TDIR}/angle 2>/dev/null
			cat ${TDIR}/badpos ${TDIR}/strange ${TDIR}/angle | \
				sort > ${TDIR}/errs_accept
			if cmp ${TDIR}/errs ${TDIR}/errs_accept >/dev/null 2>&1; then
				print -u2 "${PROG}: warning: '${CMD[@]}' caused:"
				[[ -s ${TDIR}/strange ]] && print -u2 "\t- strange path errors."
				[[ -s ${TDIR}/badpos ]] && print -u2 "\t- bad pos errors."
				[[ -s ${TDIR}/angle ]] && print -u2 "\t- angle(0,0) errors."
			else
				print -u2 "${PROG}: '${CMD[@]}' failed."
				return 1
			fi
		fi
	fi

	# hbf2gf just produces a .pl file:
	[[ -r ${NAME}.pl ]] && pltotf "${NAME}.pl" ${TFMNAME} 1>&2
	[[ ! -r ${TFMNAME} ]] && \
		print -u2 "${PROG}: '${CMD[@]}' failed to make '${TFMNAME}'." && \
		return 1

	# Install TFM file carefully, since others may be working simultaneously.
	if [[ ! -f ${TFMDESTDIR}/${TFMNAME} ]]; then
		cp -f "${TFMNAME}" ${TFMDESTDIR}/tfm$$.tmp || return 1
		chmod 0644 ${TFMDESTDIR}/tfm$$.tmp
		mv ${TFMDESTDIR}/tfm$$.tmp "${TFMDESTDIR}/${TFMNAME}" || return 1
	fi

	# OK, success with the TFM.
	"${MT_MKTEXUPD}" ${TFMDESTDIR} ${TFMNAME} 1>&2
	print "${TFMDESTDIR}/${TFMNAME}"
	print -u2 "${PROG}: '${TFMDESTDIR}/${TFMNAME}' successfully generated."

	# Since we probably made a GF(->PK) file, too, may as well install it if
	# it's needed.
	if [[ -r ${GFNAME} && ! -f ${PKDESTDIR}/${PKNAME} ]] then
		cd ${TDIR}
		gftopk ${GFNAME} ${PKNAME} || return 1
		"${MT_MKTEXDIR}" ${PKDESTDIR} 1>&2
		cp ${PKNAME} ${PKDESTDIR}/pk$$.tmp || return 1
		chmod 0644 ${PKDESTDIR}/pk$$.tmp
		mv ${PKDESTDIR}/pk$$.tmp ${PKDESTDIR}/${PKNAME}
		"${MT_MKTEXUPD}" ${PKDESTDIR} ${PKNAME} 1>&2
	fi
	return 0
}

USAGE='[-?'"${VERSION}"' ]
[-author?Thomas Esser, Karl Berry, and Olaf Weber]
[-author?Jens Elkner (2015 ksh93 port/cleanup)]
[-license?Public domain.]
[+NAME?'"${PROG}"' - create a Tex Font Metric (TMF) file]
[+DESCRIPTION?'"${PROG}"' makes a TFM file for \afont\a, if possible.]
[+?'"${PROG}"' is typically called by other programs, rather than from the command line. Therefore it will only print the path of the created font file to stdout, everything else goes to stderr.]
[+BUGS?Report bugs to: tex-k@tug.org]
[+?TeX Live home page: \bhttp://tug.org/texlive/\b]
[h:help?Print this help and exit.]
[F:functions?Print a list of all functions available.]
[T:trace]:[fnList?A comma separated list of functions of this script to trace (convinience for troubleshooting).]
[+?]
[d:destdir]:[directory?Write fonts to the given \adirectory\a.]
[V:version?Print version info for this script and exit.]
\n\n\afont\a
'
DEST=
X="${ print ${USAGE} ; }"
while getopts "${X}" OPT ; do
	case ${OPT} in
		h) showUsage ; exit 0 ;;
		T)	if [[ ${OPTARG} == 'ALL' ]]; then
				typeset -ft ${ typeset +f ; }
			else
				typeset -ft ${OPTARG//,/ }
			fi
			;;
		F) typeset +f && exit 0 ;;
		d) DEST="${OPTARG}" ;;
		V) print -u2 "${PROG}  ${VERSION}" ; exit 0 ;;
		*) showUsage 1 ; exit 1 ;
	esac
done
X=$((OPTIND-1))
shift $X && OPTIND=1
unset X

trap cleanup EXIT
doMain "$@"
