#!/usr/bin/env bash
# LFS comes with bash, which allows a simple 'which'
# Configure my TeX tests, according to what is available.
# FreeBSD-10.1's shell feels more like csh than POSIX, but
# after installing a desktop and texlive, I found that
# bash had been installed in /usr/local, so try that.
# Copyright © 2014-2016 Ken Moffat <ken@linuxfromscratch.org>
# licensed under the GNU GPL v2 License:
# https://gnu.org/licenses/old-licenses/gpl-2.0.html
# Best viewed in a term 100+ columns wide

VERSION=$(cat ./VERSION)
MAXTESTS=17 # for reporting how many can be run, FIXME increase if adding more tests
# for testing on a fully-provisioned system, --without-something
# will be useful to check the logic.
# by default, test for everything - pdflatex will always be required.
TESTASY=yes
TESTBIBER=yes
TESTBIBTEX=yes
TESTBIDIPOEM=yes
TESTCONTEXT=yes
TESTCYL=yes
TESTLUALATEX=yes
TESTMAKEINDEX=yes
TESTPDF=yes
TESTRUBY=yes
TESTTRI=yes
TESTXELATEX=yes
TESTXINDY=yes
TESTXINDYNONLUA=yes
TESTFONTS=yes
TESTCHINESE=yes
TESTJAPANESE=yes
TESTKOREAN=yes

BADPARM=

MAINFONT=
POEMFONT=
CFONT=
JFONT=
KFONT=
PREFER=japanese # it has to default to something.

check_omit_parm () {
	PARM=$(echo $1 | sed 's/--without-//')
	if [ "$PARM" = "asy" ]; then
		TESTASY=
	elif [ "$PARM" = "biber" ]; then
		TESTBIBER=
	elif [ "$PARM" = "bibtex" ]; then
		TESTBIBTEX=
	elif [ "$PARM" = "bidipoem" ]; then
		TESTBIDIPOEM=
	elif [ "$PARM" = "context" ]; then
		TESTCONTEXT=
	elif [ "$PARM" = "cylinder" ]; then
		TESTCYL=
	elif [ "$PARM" = "lualatex" ]; then
		TESTLUALATEX=
	elif [ "$PARM" = "makeindex" ]; then
		TESTMAKEINDEX=
	elif [ "$PARM" = "ruby" ]; then
		TESTRUBY=
	elif [ "$PARM" = "tikz" ]; then
		TESTTIKZ=
	elif [ "$PARM" = "triangles" ]; then
		TESTTRI=
	elif [ "$PARM" = "xelatex" ]; then
		TESTXELATEX=
	elif [ "$PARM" = "xindy" ]; then
		TESTXINDY=
		TESTXINDYNONLUA=
	elif [ "$PARM" = "fonts" ]; then
		TESTFONTS=
	elif [ "$PARM" = "chinese" ]; then
		TESTCHINESE=
	elif [ "$PARM" = "japanese" ]; then
		TESTJAPANESE=
	elif [ "$PARM" = "korean" ]; then
		TESTKOREAN=
	else
		BADPARM="$BADPARM $PARM"
	fi
}

check_font_parm () {
	# allow user to force a font, at their own risk
	FONTVAL=$(echo "$1" | cut -d '=' -f 2)
	FONTTYPE=$(echo $1 | sed -e 's%^--with-%%' -e 's%-font=.*$%%')
	if [ "$FONTTYPE" = "main" ]; then
		MAINFONT="$FONTVAL"
	elif [ "$FONTTYPE" = "chinese" ]; then
		CFONT="$FONTVAL"
	elif [ "$FONTTYPE" = "japanese" ]; then
		JFONT="$FONTVAL"
	elif [ "$FONTTYPE" = "korean" ]; then
		KFONT="$FONTVAL"
	elif [ "$FONTTYPE" = "poem" ]; then
		POEMFONT=$FONTVAL
	else
		BADPARM="$BADPARM $1"
	fi
}

check_prefer () {
	LANG=$(echo "$1" | cut -d '=' -f 2)
	case $LANG in chinese|japanese)
		PREFER=$LANG
		;;
	*)
		echo "ERROR: --prefer= only accepts chinese or japanese"
		exit 1
		;;
	esac
}

sysfont () {
# $1 is the font file name (it saves trying to work out if the 'regular'
# variant is installed), Mostly, the Regular variant has Style=Regular,
#but for some of the Chinese fonts the Style is Book or Light, and
# freefont gives a multilingual string, fortunately beginning Regular
#
# If file is found, return the name else return empty string
# the 2>/dev/null is because on a system using fontconfig-2.11.0 I was
# getting a message on the output for every invocation of fc-list:
# Fontconfig warning: ignoring chinese: not a valid language tag
# this used to be called with the name to use as the second parm,
# but now return that,
if [ $# -ne 1 ]; then
	echo "BAD CALL to sysfont : $*"
	exit 2
fi
if [ -n "$FCLIST" ]; then
	fc-list 2>/dev/null | grep -q $1
	if [ $? -eq 0 ]; then
		# now work out the best match (prefer Regular,
		# but Book for UKai, Light for UMing)
		FNAME=$1
		# add enough to get the simplified, or the non-monospace
		echo $1 | grep -qi ukai  && FNAME="$1.*CN"
		echo $1 | grep -qi uming && FNAME="$1.*CN"
		echo $1 | grep -qi odosung && FNAME="$1: AR PL New Sung,"
		echo $1 | grep -qi wqy-zenhei && FNAME="$1: WenQuanYi Zen Hei,"
		FONTWORK=$(fc-list 2>/dev/null | grep "${FNAME}.*style=Regular")
		if [ -z "$FONTWORK" ]; then
			FONTWORK=$(fc-list 2>/dev/null | grep "${FNAME}.*style=Book")
		fi
		if [ -z "$FONTWORK" ]; then
			FONTWORK=$(fc-list 2>/dev/null | grep "${FNAME}.*style=Light")
		fi
		# VL-Gothic is 'regular' with a small r
		if [ -z "$FONTWORK" ]; then
			FONTWORK=$(fc-list 2>/dev/null | grep "${FNAME}.*style=regular")
		fi
		# the sawarabi fonts are Medium
		if [ -z "$FONTWORK" ]; then
			FONTWORK=$(fc-list 2>/dev/null | grep "${FNAME}.*style=Medium")
		fi
		# bail if a font exists but was not matched to the type
		if [ -z "$FONTWORK" ]; then
			echo "Error: no suitable style found for $FNAME" >&2
		fi
		# take the part between ': ... :', up to any comma,
		# and remove the leading space
		FONTNAME=$(echo $FONTWORK | cut -d ':' -f2 | cut -d ',' -f1 \
		 | sed 's/^ *//')
		echo -n "$FONTNAME"
		#echo >&2 "FONTWORK is $FONTWORK"
		#echo >&2 "FONTNAME is $FONTNAME"
	else
		echo -n ''
	fi
else
	echo -n ''
fi
}

texfont () {
# for testing : ensure no texlive fonts are found		
# for fontconfig it is fairly easy to move fonts around,	
# but with tex that is not true.				
#DUMMY=true							
# if $1 is found below $TEXFONTS return it, else return empty string
if [ -z "$TEXFONTS" ] || [ -n "$DUMMY" ]; then
	echo -n ''
else
# set TEXDEBUG for debugging - it may break the seds which set font names
	if [ -n "$TEXDEBUG" ]; then
		echo "Running find $TEXFONTS -name $1 | sed 's%^.*/%%' "
		RESULT=$(find $TEXFONTS -name $1 | sed 's%^.*/%%')
		echo $RESULT
		echo
	fi
	echo -n $(find $TEXFONTS -name $1 | sed 's%^.*/%%')
fi
}

check_for () {
	# use kpsewhich to check if a sty file is present
	# call with name without .sty and variablename
	# on success, variable is set to 0
	# otherwise to 1
	if [ $# -ne 2 ]; then
		echo "INTERNAL ERROR: check_for called with $*"
		exit 2
	fi
	echo -n "testing for $1 ... "
	kpsewhich $1.sty >/dev/null
	if [ $? -eq 0 ]; then
		echo "yes"
		let $2=0
	else
		echo "no"
		let $2=1
	fi
}

exists () {
	# check if a program is found
	if [ $# -ne 1 ]; then
		echo "exists was called with $*"
		exit 2
	fi
	echo -n "checking for $1 ... "
	type -pa $1
	if [ $? -eq 0 ]; then
		return 0
	else
		echo "no"
		return 1
	fi
}

desire () {
	# test if an optional TeX program exists,
	# populate variable with its name if it does
	# report what cannot be run if it doesn't.
	# and issue a warning
	# args progname VARNAME 'fu and bar'
	if [ $# -ne 3 ]; then
		echo "desire called with $# args: $*"
		exit 2
	fi
	exists $1
	if [ $? -eq 0 ]; then
		declare -g "$2=$1"
	else
		echo "WARNING: I need $1 to run $3"
		let WARNINGS=$WARNINGS+1
	fi
}
# - - - - - - - - - - - - - - - - - - - -
# main line

echo "This is the configure script for latex-test $VERSION"

ERRORS=0
WARNINGS=0

# first check the basic system
echo "Preparing to create the LaTeX test scripts"
echo "checking prerequisites"

# bash, as with any decent shell, has echo -n
# no need to probe for deficiencies

exists cat || let ERRORS=$ERRORS+1
exists grep || let ERRORS=$ERRORS+1
exists make || let ERRORS=$ERRORS+1
exists pdfinfo || let ERRORS=$ERRORS+1
exists pdftotext || let ERRORS=$ERRORS+1
exists rm || let ERRORS=$ERRORS+1
exists sed || let ERRORS=$ERRORS+1
exists X || let ERRORS=$ERRORS+1
exists kpsewhich || let ERRORS=$ERRORS+1
exists pdflatex || let ERRORS=$ERRORS+1

if [ $ERRORS -gt 0 ]; then
	echo "ERROR: your basic kit is not complete"
	echo "As well as shell tools, I need X and fontconfig"
	echo "plus pdfinfo and pdftotext from poppler to check"
	echo "if xindy and biber work"
	echo "and a latex install with a PDF viewer"
	exit 1
fi

# now check for a PDF viewer
# anyone will do
echo "looking for a known PDF viewer"
exists epdfview || \
 exists mupdf || \
  exists evince || \
   exists atril || \
    exists okular || \
     exists xpdf || \
      echo "I hope you have a PDF viewer"

# - - - - - - - - - - - - - - - - - - - -
# Now check that only ONE texlive is on $PATH
# if more than one, most tests seem to pass but
# the duplicated match_parens causes a sed to
# fail with an odd message.  The point is that
# with muiltiple texlive instances the tests
# might find things from the non-default instance,
# e.g. if the first version on $PATH is incomplete.
INSTANCES=$(type -pa pdflatex | wc -l)
if [ $INSTANCES -gt 1 ]; then
	echo "ERROR: more than one instance texlive is present on PATH"
	echo "found pdflatex at:"
	type -pa pdflatex
	echo "Please fix this to test the desired version."
	exit 2
fi

# - - - - - - - - - - - - - - - - - - - -
echo "checking any switches you supplied"
# if any parms were supplied, sed will be required.
while [ $# -gt 0 ]; do
	echo "\$1 is now $1"
	case $1 in	--without-*)
				check_omit_parm $1
				;;
			--with-*-font=*) # needs double quotes for spaces
				check_font_parm "$1"
				;;
			*)
				BADPARM="$BADPARM $1"
				;;
	esac
	shift
done

# - - - - - - - - - - - - - - - - - - - -
# now check the optional TeX programs and any related other progs
echo "checking for optional TeX programs"

if [ -n "$TESTASY" ]; then
	desire asy ASY 'triangles (2D diagram)'
	if [ -n "$ASY" ]; then
		# asy uses gs at runtime
		desire gs GS "triangles (2D diagram)"
	fi
else
	echo "asy and cylinder deselected by request"
fi
# repeat for cylinder, which requires asy but can be separately disabled
if [ -n "$TESTCYL" ] && [ -n "$TESTASY" ]; then
	desire asy CYL "cylinder (3D diagram)"
# the ele is covered by the else message for TESTASY above
#else
#	echo "cylinder deselected by request"
fi

if [ -n "$TESTBIBER" ]; then
	desire biber BIBER 'several tests'
else
	echo "biber deselected by request"
fi

if [ -n "$TESTBIBTEX" ]; then
	desire bibtex BIBTEX 'biblatex-bibtex and bibtex tests'
else
	echo "bibtex deselected by request"
fi

if [ -n "$TESTLUALATEX" ]; then
	desire lualatex LUALATEX 'context, lualatex, xindy tests'
else
	echo "lualatex deselected by request"
fi

if [ -n "$LUALATEX" ]; then
	desire luaotfload-tool LUAOTFLOADTOOL 'to ensure fontspec can find fonts for lualatex'

	if [ -n "$TESTXINDY" ]; then
		desire makeglossaries MAKEGLOSSARIES 'xindy'
		if [ -n "$MAKEGLOSSARIES" ]; then
			desire xindy XINDY 'xindy'
		fi
		desire pdfinfo PDFINFO 'check to confirm xindy succeeded'
	else
		echo "xindy deselected by request"
	fi

	if [ -n "$TESTCONTEXT" ]; then
		desire context CONTEXT 'context'
		if [ -n "$CONTEXT" ]; then
			# there are a lot of reports for 2014 about broken versions of
			# context, and I have found two myself. so test it.
			# the reputed fix, as root, is:
			# sudo tlmgr [ might need a repository ? ] update context luatex metapost
			# sudo luatools --generate && mtxrun --generate
			STATUS=$(context --version >/dev/null 2>&1)
			if [ $? -ne 0 ]; then
				echo "WARNING: your context does not work, context test disabled"
				unset CONTEXT
			fi
		fi
	else
		echo "context deselected by request"
	fi
fi

if [ -n "$TESTMAKEINDEX" ]; then
	desire makeindex MAKEINDEX 'bibtex'
else
	echo "bibtex deselected by request"
fi

# xindynonlua can be run without lualatex / fonts
if [ -n "$TESTXINDYNONLUA" ]; then
	desire texindy TEXINDY 'xindynonlua'
	if [ -n "$TEXINDY" ]; then
		test -n $PDFINFO || desire pdfinfo PDFINFO 'check to confirm xindynonlua succeeded'
	fi
else
	echo "xindynonlua deselected by request"
fi

if [ -n "$TESTXELATEX" ]; then
	desire xelatex XELATEX 'various UTF-8 tests'
else
	echo "xelatex deselected by request"
fi

if [ -n "$TESTRUBY" ]; then
	desire ruby RUBY 'parens'
	if [ -n "$RUBY" ]; then
		desire match_parens MATCHPARENS 'parens'
	fi
else
	echo "ruby (i.e. match_parens) deselected by request"
fi

# - - - - - - - - - - - - - - - - -
# all fonts are tested in order of preference.
# indentation here is reduced!

# check for fonts for lualatex and xelatex
if [ -z "$TESTFONTS" ]; then
	echo "All TTF/OTF fonts deselected by request"
fi

if [ -n "$TESTFONTS" ]; then
	echo "Checking for useful TTF/OTF fonts for lualatex or xelatex"
	if [ -n "$LUALATEX" ] || [ -n "$XELATEX" ]; then
		echo "looking to see if I can search for texlive fonts"
		exists kpsepath && KPSEPATH=kpsepath
		exists tr && TR=tr
		if [ -z "$KPSEPATH" ] || [ -z "$TR" ]; then
			echo "I need both kpsepath and tr to find texlive OTF/TTF fonts"
		fi
	fi
fi

if [ -z "$LUALATEX" ] && [ -z "$XELATEX" ] && [ -n "$TESTFONTS" ]; then
	echo "neither lualatex nor xelatex will be used, not testing for fonts"
	TESTFONTS=
fi
if [ -n "$TESTFONTS" ]; then
	# do not test for fc-list if it is unlikely to be needed,
	# but if it is not present drop anything using OTF/TTF fonts,
	# even if they might be found in texlive - that is to keep the
	# logic manageable.
	echo "looking to see if I can search for system fonts"
	exists fc-list && FCLIST=fc-list
	if [ -z "$FCLIST" ]; then
		echo "no"
		echo "WARNING, fc-list not found, cannot check system fonts"
		let WARNINGS=$WARNINGS+1
	fi

	# check for texlive fonts
	if [ -n "$KPSEPATH" ] && [ -n "$TR" ]; then
		DISTFONTS=$(kpsepath vf | tr ':' '\n' | grep 'texmf-dist/fonts' | \
		 head -n 1 | sed -e 's%^!*%%' -e 's%\(fonts/\).*%\1%')
		if [ -z "$DISTFONTS" ]; then
			echo "cannot determine where texlive fonts are"
		elif [ -d "$DISTFONTS" ]; then
			# assume the fonts directory might not exist!
			TEXFONTS=$DISTFONTS
		else
			echo "cannot find texlive fonts : will only check fontconfig"
		fi
	fi

    if [ -n "$MAINFONT" ]; then
	# font was requested, confirm it exists and convert to name
	# NB when the Name is specified (instead of the filename), do NOT use
	# sysfont.
	MAINFONT=$(sysfont "$MAINFONT")
	if [ -z "$MAINFONT" ]; then
		echo "ERROR: specified main font $MAINFONT not found"
		exit 1
	else
		echo "will use $MAINFONT for main text in lualatex and xelatex"
	fi
    else
	# begin by looking for useful texlive fonts : i.e. those which contain
	# all of the latin/greek/cyrillic letters which I might use.
	# initially, just store the file names because that is how xelatex will
	# have to access them, and that also works for lualatex.
	if [ -n "$TEXFONTS" ]; then
		echo "Will search for specific fonts in $TEXFONTS, this may take some time"
	fi
	MAINFONT=$(texfont fubar.ttf) # test that texfont works for non-existant font
	test -z "$MAINFONT" && MAINFONT=$(texfont LinLibertine_R.otf)
	test -z "$MAINFONT" && MAINFONT=$(texfont DejaVuSerif.ttf)
	test -z "$MAINFONT" && MAINFONT=$(texfont FreeSerif.otf)

	if [ -z "$MAINFONT" ] && [ -n "$TEXFONTS" ]; then # did not find any useful texlive fonts
		echo "no useful texlive fonts were found"
	fi
	# There are better fonts than these, but these two are common
	# AND have adequate coverage including cyrillic, greek, vietnamese
	test -z "$MAINFONT" && MAINFONT=$(sysfont DejaVuSerif.ttf)
	test -z "$MAINFONT" && MAINFONT=$(sysfont FreeSerif.otf)

	if [ -z "$MAINFONT" ]; then
		echo "Neither DejaVu Serif nor FreeSerif were found - OTF/TTF will not be used"
		let WARNINGS=$WARNINGS+1
	else
		 echo "will use $MAINFONT for non-CJK text in lualatex and xelatex"
	fi
    fi

fi
# repeat for the various CJK options, if TESTFONTS and MAINFONT both set
if [ -n "$TESTFONTS" ] && [ -n "$MAINFONT" ]; then
    # For CJK, use common free fonts.
    # Note that these fonts seem to only support one of chinese, japanese,
    # korean.

    if [ -n "$CFONT" ]; then
	# font was requested, confirm it exists
	CFONT=$(sysfont "$CFONT")
	if [ -z "$CFONT" ]; then
		echo "ERROR: specified chinese font $CFONT not found"
		exit 1
	else
		echo "will use specified font $CFONT for chinese text"
	fi
    else
        # Use system fonts - Ming and Sung should be preferred, but Kai is also
	# good before falling back to Hei (Sans).  N.B. the old fireflysung is
	# a traditional font, odosung replaces it and covers simplified.
        if [ -n "$TESTCHINESE" ]; then
            echo -n "Looking for a Simplified Chinese font ... "
	    # begin with Ming/Song/Sung (serif)
	    test -z "$CFONT" && CFONT=$(texfont FandolSong-Regular.otf )
	    # for a ttc, we can specify which included name we wish to use
	    test -z "$CFONT" && CFONT=$(sysfont uming.ttc )
	    test -z "$CFONT" && CFONT=$(sysfont gbsn00lp.ttf )
	    test -z "$CFONT" && CFONT=$(sysfont odosung.ttc )
	    # now try Kai (script)
	    test -z "$CFONT" && CFONT=$(sysfont ukai.ttc )
	    test -z "$CFONT" && CFONT=$(sysfont gkai00mp.ttf )
	    test -z "$CFONT" && CFONT=$(sysfont odokai.ttf )
	    # now try Hei (sans)
	    test -z "$CFONT" && CFONT=$(texfont FandolHei-Regular.otf )
	    test -z "$CFONT" && CFONT=$(sysfont NotoSansCJKsc-Regular.otf )
	    test -z "$CFONT" && CFONT=$(sysfont odohei.ttf )
	    test -z "$CFONT" && CFONT=$(sysfont wqy-zenhei.ttc )
	    # the version of Droid Sans that includes Chinese and Japanese
	    test -z "$CFONT" && CFONT=$(sysfont DroidSansFallbackFull.ttf )
            if [ -n "$CFONT" ]; then
                echo "$CFONT"
            else
                echo "WARNING: None found"
                let WARNINGS=$WARNINGS+1
            fi
        else
	    echo "chinese deselected"
        fi
    fi

    if [ -n "$JFONT" ]; then
	# font was requested, confirm it exists
	JFONT=$(sysfont "$JFONT")
	if [ -z "$JFONT" ]; then
		echo "ERROR: specified japanese font $JFONT not found"
		exit 1
	else
		echo "will use specified font $JFONT for japanese text"
	fi
    else
        if [ -n "$TESTJAPANESE" ]; then
            echo -n "Looking for a Japanese font ... "
	    # first. try mincho (serif)
	    # begin with ipaexm which is the modern version of ipam, including
	    # proportional-width letters for english text
	    test -z "$JFONT" && JFONT=$(texfont ipaexm.ttf)
	    test -z "$JFONT" && JFONT=$(sysfont ipaexm.ttf )
	    test -z "$JFONT" && JFONT=$(texfont ipam.ttf)
	    test -z "$JFONT" && JFONT=$(sysfont ipam.ttf)
	    # continue with other known mincho fonts
	    test -z "$JFONT" && JFONT=$(sysfont HanaMinA.ttf )
	    test -z "$JFONT" && JFONT=$(sysfont kochi-mincho-subst.ttf )
	    # for non-obvious reasons, lualatex (tl2015) cannot find Sawarabi Moncho
	    # although xelatex is fine with it.
	    #test -z "$JFONT" && JFONT=$(sysfont sawarabi-mincho-medium.ttf )
	    # then try gothic (sans)
	    # again, try ipaex before ipa
	    test -z "$JFONT" && JFONT=$(texfont ipaexg.ttf)
	    test -z "$JFONT" && JFONT=$(sysfont ipaexg.ttf )
	    test -z "$JFONT" && JFONT=$(texfont ipag.ttf)
	    test -z "$JFONT" && JFONT=$(sysfont ipag.ttf )
	    # then try vlgothic which is currently maintained
	    test -z "$JFONT" && JFONT=$(sysfont VL-Gothic-Regular.ttf )
	    test -z "$JFONT" && JFONT=$(sysfont NotoSansCJKjp-Regular.otf )
	    test -z "$JFONT" && JFONT=$(sysfont kochi-gothic-subst.ttf )
	    test -z "$JFONT" && JFONT=$(sysfont sawarabi-gothic-medium.ttf )
	    # try pan-unicode fonts as a fallback (i.e. chinese, but they do cover japanese)
	    test -z "$JFONT" && JFONT=$(sysfont wqy-zenhei.ttc )
	    test -z "$JFONT" && JFONT=$(sysfont DroidSansFallbackFull.ttf )
            if [ -n "$JFONT" ]; then
                echo "$JFONT"
            else
                echo "WARNING: None found"
                let WARNINGS=$WARNINGS+1
            fi
        else
	    echo "japanese deselected"
        fi
    fi

    if [ -n "$KFONT" ]; then
	# font was requested, confirm it exists
	KFONT=$(sysfont "$KFONT")
	if [ -z "$KFONT" ]; then
		echo "ERROR: specified korean font $KFONT not found"
		exit 1
	else
		echo "will use specified font $KFONT for korean text"
	fi
    else
        if [ -n "$TESTKOREAN" ]; then
            echo -n  "Looking for a Korean font ... "
            # Only system fonts can be used for korean.
            # As elsewhere, prefer serif-equivalent to sans,
	    # then fall back to one chinese pan-unicode font
	    # (Droid Sand Fallback does not include hangul glyphs).
	    # serif
	    test -z "$KFONT" && KFONT=$(sysfont batang.ttf )
	    test -z "$KFONT" && KFONT=$(sysfont NanumMyeongjo.ttf )
	    test -z "$KFONT" && KFONT=$(sysfont UnBatang.ttf )
	    # sans
	    test -z "$KFONT" && KFONT=$(sysfont dotum.ttf )
	    test -z "$KFONT" && KFONT=$(sysfont gulim.ttf )
	    test -z "$KFONT" && KFONT=$(sysfont NanumGothic.ttf )
	    test -z "$KFONT" && KFONT=$(sysfont UnDotum.ttf )
	    test -z "$KFONT" && KFONT=$(sysfont UnGraphic.ttf )
	    test -z "$KFONT" && KFONT=$(sysfont NotoSansCJKkr-Regular.otf )
	    # unusually, all of the Noto Sans CJK variants include korean
	    test -z "$KFONT" && KFONT=$(sysfont NotoSansCJKjp-Regular.otf )
	    test -z "$KFONT" && KFONT=$(sysfont NotoSansCJKsc-Regular.otf )
	    test -z "$KFONT" && KFONT=$(sysfont NotoSansCJKtc-Regular.otf )
	    # pan-unicode
	    test -z "$KFONT" && KFONT=$(sysfont wqy-zenhei.ttc )
            if [ -n "$KFONT" ]; then
                echo "$KFONT"
            else
                echo "WARNING: None found"
                let WARNINGS=$WARNINGS+1
            fi
        else
	    echo "korean deselected"
        fi
    fi
fi

# if we are not testing xelatex, do not test font for poems
if [ -n "$TESTFONTS" ] && [ -n "$XELATEX" ] && [ -n "$TESTBIDIPOEM" ]; then
    if [ -n "$POEMFONT" ]; then
	# font was requested, confirm it exists
	test -n "$FCLIST" && fc-list 2>/dev/null | grep -q "$POEMFONT"
	if [ $? -ne 0 ]; then
		echo "ERROR: specified poem font $POEMFONT not found"
		exit 1
	else
		echo "will use specified font $POEMFONT for bidipoem"
	fi
    else
	echo -n "Looking for a font for english/persian poems: "
	# persian modern regular used to be supplied with texlive
	# but is no longer included.
	test -z "$POEMFONT" && POEMFONT=$(texfont persian-modern-regular.ttf)
	# FreeSerif is supplied with texlive or might have been installed
	test -z "$POEMFONT" && POEMFONT=$(texfont FreeSerif.otf)
	test -z "$POEMFONT" && POEMFONT=$(sysfont FreeSerif.otf )
	# similarly, DejaVu Sans might be from texlive or system
	test -z "$POEMFONT" && POEMFONT=$(texfont DejaVuSans.ttf)
	test -z "$POEMFONT" && POEMFONT=$(sysfont DejaVuSans.ttf )
	# NB neither nazli nor FreeFarsi will support the English text in my
	# example (fancy double-quotes and apostrophe are missing).
	if [ -n "$POEMFONT" ]; then
		echo $POEMFONT
	else
		TESTBIDIPOEM=
		echo "no suitable font found, cannot test bidipoem"
	fi
    fi
fi

# - - - - - - - - - - - - - - - - -
# for safety, now check that all used packages have been installed.
echo "checking for ALL installed latex packages which MIGHT be used"
echo "if any are not found but you know they are present, please rerun mktexlsr"

check_for asymptote HAVEASYMPTOTE

check_for babel HAVEBABEL

check_for biblatex HAVEBIBLATEX

check_for bidi HAVEBIDI

check_for bidipoem HAVEBIDIPOEM

check_for bookmark HAVEBOOKMARK

check_for circuitikz HAVECIRCUITIKZ

check_for combelow HAVECOMBELOW

check_for csquotes HAVECSQUOTES

check_for fancyhdr HAVEFANCYHDR

check_for fontenc HAVEFONTENC

check_for fontspec HAVEFONTSPEC

check_for geometry HAVEGEOMETRY

check_for glossaries HAVEGLOSSARIES

check_for hyperref HAVEHYPERREF

check_for idxlayout HAVEIDXLAYOUT

check_for imakeidx HAVEIMAKEIDX

check_for inputenc HAVEINPUTENC

check_for luacode HAVELUACODE

check_for lipsum HAVELIPSUM

check_for makeidx HAVEMAKEIDX

check_for metalogo HAVEMETALOGO

check_for microtype HAVEMICROTYPE

check_for natbib HAVENATBIB

# pgfbaseimage is the main package for TikZ
check_for pgfbaseimage HAVETIKZ

# try to see if blend mode is supported
TIKZCODE=$(kpsewhich tikz.code.tex)
if [ -n "$TIKZCODE" ]; then
	echo -n "looking to see if blend mode is supported ... "
	grep -q 'blend mode' $TIKZCODE
	if [ $? -eq 0 ]; then
		echo "yes"
		HAVEBLEND=0
	else
		echo "no"
		HAVEBLEND=1
	fi
fi

check_for ragged2e HAVERAGGED2E

check_for savetrees HAVESAVETREES

check_for setspace HAVESETSPACE

check_for siunitx HAVESIUNITX

check_for tipa HAVETIPA

check_for url HAVEURL

check_for verbatim HAVEVERBATIM

check_for xcolor HAVEXCOLOR

check_for xeCJK HAVEXECJK

# now, disable any enabled target for which required packages are missing

let ENABLED=0

# deps for triangles.tex which uses asy
RUNTRI=1
test -n "$TRI" && test $HAVEASYMPTOTE -eq 0 || TESTTRI=
# asy needs gs at runtime
test -n "TRYASY" && test -n "$GS" || TESTASY=
if [ -n "$TESTASY" ]; then
	RUNTRI=0
	let ENABLED=$ENABLED+1
fi
# cylinder is another asy test, with different deps
RUNCYL=1
if [ -n "$TESTASY" ] && [ -n "$TESTCYL" ]; then
	if [ -n "$GS" ] && [ -n "$CYL" ]; then
		RUNCYL=0
		let ENABLED=$ENABLED+1
	fi
fi

# biblatex.in deps for biblatex-biber and biblatex-bibtex
# for biblatex-biber and biblatex-bibtex, at the moment various
# variables are used for more than one thing.
# set up TESTBIBLB and TESTBIBLT
# so need to test if the backend progs exist
# assume they do not
RUNBIBLB=1
RUNBIBLT=1
if [ $HAVEBIBLATEX -eq 0 ] && [ $HAVECOMBELOW -eq 0 ] && [ $HAVERAGGED2E -eq 0 ]; then
	if [ -n "$BIBER" ]; then
		RUNBIBLB=0
		let ENABLED=$ENABLED+1
	fi
	if [ -n "$BIBTEX" ]; then
		RUNBIBLT=0
		let ENABLED=$ENABLED+1
	fi
fi

# biblatex-unibiber.tex deps
# similarly, biblatex-unibiber is determined by BIBER so set RUNBIBLU
# try setting test var if biber exists, then unset on first missing dep
RUNBIBLU=1
test -n "$BIBER" && TRYBIBLU=1
test -n "$TRYBIBLU" && test $HAVEBIBLATEX -eq 0 || TRYBIBLU=
test -n "$TRYBIBLU" && test $HAVEINPUTENC -eq 0 || TRYBIBLU=
test -n "$TRYBIBLU" && test $HAVEFONTENC -eq 0 || TRYBIBLU=
test -n "$TRYBIBLU" && test $HAVESAVETREES -eq 0 || TRYBIBLU=
test -n "$TRYBIBLU" && test $HAVECSQUOTES -eq 0 || TRYBIBLU=
test -n "$TRYBIBLU" && test $HAVEBOOKMARK -eq 0 || TRYBIBLU=
if [ -n "$TRYBIBLU" ]; then
	RUNBIBLU=0
	let ENABLED=$ENABLED+1
fi

# bibtexidx.tex deps
RUNBTX=1
if [ -n "$BIBTEX" ] && [ -n "$MAKEINDEX" ]; then
	TRYBTX=1
fi
test -n "$TRYBTX" && test $HAVEMAKEIDX -eq 0 || TRYBTX=
test -n "$TRYBTX" && test $HAVENATBIB -eq 0 || TRYBTX=
test -n "$TRYBTX" && test $HAVESETSPACE -eq 0 || TRYBTX=
test -n "$TRYBTX" && test $HAVEURL -eq 0 || TRYBTX=
if [ -n "$TRYBTX" ]; then
	RUNBTX=0
	let ENABLED=$ENABLED+1
fi


# bibxelatex.in deps
# use TRYBIBXEL to identify that the required packages are present
# this will NOT prove that the necessary other deps are present
# so move those tests to just after this.
RUNBIBXELATEX=1
test -n "$BIBER" && TRYBIBXEL=1
test -n "$TRYBIBXEL" && test -n "$XELATEX" || TRYBIBXEL=
test -n "$TRYBIBXEL" && test $HAVEBIBLATEX -eq 0 || TRYBIBXEL=
test -n "$TRYBIBXEL" && test $HAVEFONTSPEC -eq 0 || TRYBIBXEL=
test -n "$TRYBIBXEL" && test $HAVECSQUOTES -eq 0 || TRYBIBXEL=
test -n "$TRYBIBXEL" && test $HAVEBABEL -eq 0 || TRYBIBXEL=
test -n "$TRYBIBXEL" && test $HAVEXECJK -eq 0 || TRYBIBXEL=
if [ -n "$TRYBIBXEL" ]; then
	# bibxelatex needs BIBER and both CFONT AND JFONT
	if [ -n "$BIBER" ] && [ -n "$CFONT" ] && [ -n "$JFONT" ]; then
		RUNBIBXELATEX=0
		let ENABLED=$ENABLED+1
	fi
fi

# bidipoem.in deps
# NB TESTBIDIPOEM was turned off if no suitable font was found
RUNBIDI=1
test -n "$TESTBIDIPOEM" && TRYBIDI=1
test -n "$TRYBIDI" && test $HAVEFONTSPEC -eq 0 || TRYBIDI=
test -n "$TRYBIDI" && test $HAVEBIDI -eq 0 || TRYBIDI=
test -n "$TRYBIDI" && test $HAVEBIDIPOEM -eq 0 || TRYBIDI=
# bidipoem does not use MAINFONT, so test its deps separately
if [ -n "$XELATEX" ] && [ -n "$TESTBIDIPOEM" ]; then
	let ENABLED=$ENABLED+1
	RUNBIDI=0
fi

# blended-circles.tex depends on HAVETIKZ and HAVEBLEND
RUNBLC=1
if [ $HAVETIKZ -eq 0 ] && [ $HAVEBLEND -eq 0 ]; then
	let ENABLED=$ENABLED+1
	RUNBLC=0
fi

# lualatex.in deps
RUNLUALATEX=1
test -n "$LUALATEX" && TRYLUA=1
test -n "$TRYLUA" && test $HAVEFONTSPEC -eq 0 || TRYLUA=
test -n "$TRYLUA" && test $HAVELUACODE -eq 0 || TRYLUA=
test -n "$TRYLUA" && test $HAVESETSPACE -eq 0 || TRYLUA=
test -n "$TRYLUA" && test $HAVEMETALOGO -eq 0 || TRYLUA=
test -n "$TRYLUA" && test $HAVEMICROTYPE -eq 0 || TRYLUA=
test -n "$TRYLUA" && test $HAVESAVETREES -eq 0 || TRYLUA=
# lualatex depends on LUALATEX, MAINFONT
# and for complete coverage CFONT JFONT KFONT
if [ -n "$TRYLUA" ] && [ -n "$MAINFONT" ]; then
	RUNLUALATEX=0
	let ENABLED=$ENABLED+1
fi

# mosfet.tex deps
RUNMOS=1
if [ $HAVECIRCUITIKZ -eq 0 ] && [ $HAVESIUNITX -eq 0 ] && [ $HAVEVERBATIM -eq 0 ]; then
	let ENABLED=$ENABLED+1
	RUNMOS=0
fi

# pdflatex as a program is always required, so known to be present
# but deps for my pdflatex.tex file might be missing
RUNPDF=1
test -n "$TESTPDF" && test $HAVEGEOMETRY -eq 0 || TESTPDF=
test -n "$TESTPDF" && test $HAVEFANCYHDR -eq 0 || TESTPDF=
test -n "$TESTPDF" && test $HAVELIPSUM -eq 0 || TESTPDF=
test -n "$TESTPDF" && test $HAVESETSPACE -eq 0 || TESTPDF=
test -n "$TESTPDF" && test $HAVEXCOLOR -eq 0 || TESTPDF=
if [ -n "$TESTPDF" ]; then
	RUNPDF=0
	let ENABLED=$ENABLED+1
fi

# xelatex.in deps : it needs xelatex and a main font
RUNXELATEX=1
if [ -n "$XELATEX" ] && [ -n "$MAINFONT" ]; then
	TRYXELATEX=1
fi
test -n "$TRYXELATEX" && test $HAVEFONTSPEC -eq 0 || TRYXELATEX=
test -n "$TRYXELATEX" && test $HAVESETSPACE -eq 0 || TRYXELATEX=
if [ -n "$TRYXELATEX" ]; then
	RUNXELATEX=0
	let ENABLED=$ENABLED+1
fi

# xindy.in deps
RUNXINDY=1
if [ -n "$XINDY" ]; then
	TRYXINDY=1
fi
test -n "$TRYXINDY" && test $HAVEFONTSPEC -eq 0 || TRYXINDY=
test -n "$TRYXINDY" && test $HAVESETSPACE -eq 0 || TRYXINDY=
test -n "$TRYXINDY" && test $HAVEGLOSSARIES -eq 0 || TRYXINDY=
test -n "$TRYXINDY" && test $HAVEIMAKEIDX -eq 0 || TRYXINDY=
test -n "$TRYXINDY" && test $HAVEIDXLAYOUT -eq 0 || TRYXINDY=
test -n "$TRYXINDY" && test $HAVEHYPERREF -eq 0 || TRYXINDY=
test -n "$TRYXINDY" && test $HAVEBOOKMARK -eq 0 || TRYXINDY=
if [ -n "$TRYXINDY" ]; then
	if [  -n "$LUALATEX" ] && [ -n "$MAINFONT" ] && [ -n "$MAKEGLOSSARIES" ] && [ -n "$PDFINFO" ]; then
		RUNXINDY=0
		let ENABLED=$ENABLED+1
	fi
fi

# xindynonlua.tex deps
RUNXINDYBAS=1
if [ -n "$TEXINDY" ]; then
	TRYXINDYNON=1
fi
test -n "$TRYXINDYNON" && test -n "$PDFINFO" || TRYXINDYNON=
test -n "$TRYXINDYNON" && test $HAVETIPA -eq 0 || TRYXINDYNON=
test -n "$TRYXINDYNON" && test $HAVESETSPACE -eq 0 || TRYXINDYiNON=
test -n "$TRYXINDYNON" && test $HAVEGLOSSARIES -eq 0 || TRYXINDYNON=
test -n "$TRYXINDYNON" && test $HAVEIMAKEIDX -eq 0 || TRYXINDYNON=
test -n "$TRYXINDYNON" && test $HAVEIDXLAYOUT -eq 0 || TRYXINDYNON=
test -n "$TRYXINDYNON" && test $HAVEHYPERREF -eq 0 || TRYXINDYNON=
test -n "$TRYXINDYNON" && test $HAVEBOOKMARK -eq 0 || TRYXINDYNON=
if [ -n "$TRYXINDYNON" ]; then
	RUNXINDYBAS=0
	let ENABLED=$ENABLED+1
fi

# context apparently is self-contained
RUNCONTEXT=1
if [ -n "$CONTEXT" ]; then
	RUNCONTEXT=0
	let ENABLED=$ENABLED+1
fi

# paren depends on RUBY and MATCHPARENS
# and is driven by RUNPAREN
RUNPAREN=1
if [ -n "$RUBY" ] && [ -n "$MATCHPARENS" ]; then
	RUNPAREN=0
	let ENABLED=$ENABLED+1
fi

# - - - - - - - - - - - - - - - - -
# here document what will, and will not, be run
# as well as setting up the Makefile
echo "Summary of available tests:"

if [ $ENABLED -eq 0 ]; then
	echo "No tests can be run"
	exit 2
else
	echo "$ENABLED tests (out of $MAXTESTS) can be run:"
fi

# these should be in alphabetical order
test $RUNBIBLB -eq 0 && echo " biblatex-biber can be tested" \
 || echo " biblatex-biber will NOT be tested"
test $RUNBIBLT -eq 0 && echo " biblatex-bibtex can be tested" \
 || echo " biblatex-bibtex will NOT be tested"
test $RUNBIBLU -eq 0 && echo " biblatex-unibiber can be tested" \
 || echo " biblatex-unibiber will NOT be tested"
if [ $RUNBIBXELATEX -eq 0 ]; then
	if [ -n "$KFONT" ]; then
		echo " bibxelatex can be tested"
	else
		echo " bibxelatex can be tested, but without korean"
	fi
else
	echo " bibxelatex will NOT be tested"
fi
test $RUNBTX -eq 0 && echo " bibtexidx can be tested" || echo " bibtexidx will NOT be tested"
test $RUNBIDI -eq 0 && echo " bidipoem can be tested" || echo " bidipoem will NOT be tested"
test $RUNBLC -eq 0 && echo " blended-circles can be tested" || \
  echo " blended-circles will NOT be tested"
test $RUNCONTEXT -eq 0 && echo " context can be tested" || echo " context will NOT be tested"

test $RUNCYL -eq 0 && echo " cylinder (asy 3D) can be tested" ||
							echo " cylinder will NOT be tested"
if [ $RUNLUALATEX -eq 0 ]; then
	if [ -n "$CFONT" ] && [ -n "$JFONT" ] && [ -n "$KFONT" ]; then
		LUAMSG="completely"
	else
		LUAMSG="but not for all CJK languages"
	fi
	echo " lualatex can be tested $LUAMSG"
	if [ -n "$LUAOTFLOADTOOL" ]; then
		# If you change the available fonts, and run fc-cache,
		# everything will find them.  EXCEPT lualatex, which uses
		# luaotfload-tool to maintain its own database and will
		# make its own decision about when to update.  So force it.
		echo "- running luaotfload-tool to ensure fonts are found"
		eval $LUAOTFLOADTOOL --update
	fi
else
	echo " lualatex will NOT be tested"
fi
test $RUNMOS -eq 0 && echo " mosfet can be tested" || echo " mosfet will NOT be tested"
test $RUNPAREN -eq 0 && echo " paren can be tested" \
 || echo " paren will NOT be tested"
test $RUNPDF -eq 0 && echo " pdflatex can be tested" || echo " pdflatex will NOT be tested"
test $RUNTRI -eq 0 && echo " triangles (asy 2D) can be tested" || echo " triangles will NOT be tested"
if [ $RUNXELATEX -eq 0 ]; then
	if [ -n "$CFONT" ] && [ -n "$JFONT" ] && [ -n "$KFONT" ]; then
		XELMSG="completely"
	else
		XELMSG="but not for all CJK languages"
	fi
	echo " xelatex can be tested $XELMSG"
else
	echo " xelatex will NOT be tested"
fi
test $RUNXINDY -eq 0 && echo " xindy can be tested" || echo " xindy will NOT be tested"
test $RUNXINDYBAS -eq 0 && echo " xindynonlua can be tested" \
 || echo " xindynonlua will NOT be tested"

# - - - - - - - - - - - - - - - - -
# write the Makefile here
# NB the 'all' target means all tests which can be run

# targets on which all: depends
TBID=
TBIX=
TBLR=
TBLT=
TBLU=
TBTX=
TCON=
TCYL=
TLUA=
TMOS=
TPAR=
TTRI=
TVOC=
TXIN=
# XIB 'xindy basic' actually runs xindynonlua
# so put if after xindy
TXIB=
TXEL=

# convert actual rules to # or uncommented
RBID=#
RBIX=#
RBLC=#
RBLR=#
RBLT=#
RBLU=#
RBTX=#
RCON=#
RCYL=#
RLUA=#
RMOS=#
RPAR=#
RTRI=#
RXIN=#
RXIB=#
RXEL=#

if [ $RUNPDF -eq 0 ]; then
	TPDF=pdflatex
	RPDF=
fi

if [ $RUNTRI -eq 0 ]; then
	TTRI=triangles
	RTRI=
fi

if [ $RUNCYL -eq 0 ]; then
	TCYL=cylinder
	RCYL=
fi


if [ $RUNBIBLU -eq 0 ]; then
	TBLU=biblatex-unibiber
	RBLU=
fi

if [ $RUNBIBLB -eq 0 ]; then
	TBLR=biblatex-biber
	RBLR=
	echo "creating biblatex-biber.tex"
	sed 's/%BACKEND%/biber/g' biblatex.in >biblatex-biber.tex
fi

if [ $RUNBIBLT -eq 0 ]; then
	TBLT=biblatex-bibtex
	RBLT=
	echo "creating biblatex-bibtex.tex"
	sed 's/%BACKEND%/bibtex/g' biblatex.in >biblatex-bibtex.tex
fi

if [ $RUNBTX -eq 0 ]; then
	TBTX=bibtexidx
	RBTX=
fi

if [ $RUNBIBXELATEX -eq 0 ]; then
	echo "creating bibxelatex.tex"
	sed "s%FONT%$MAINFONT%" bibxelatex.in >bibxelatex.tex
	# PREFER defaults to japanese, only acceptable alternative is chinese
	cp bibxelatex.tex{,.bak}
	if [ "$PREFER" = "chinese" ]; then
		sed -e "s/PREFER/$CFONT/" \
		    -e "s/FALLBACK/$JFONT/" bibxelatex.tex.bak >bibxelatex.tex
	else
		sed -e "s/PREFER/$JFONT/" \
		    -e "s/FALLBACK/$CFONT/" bibxelatex.tex.bak >bibxelatex.tex
	fi
	cp bibxelatex.tex{,.bak}
	if [ -n "$KFONT" ]; then
		sed "s%KOREAN%$KFONT%" bibxelatex.tex.bak >bibxelatex.tex
	else
		sed '/ %KR%/d' bibxelatex.tex.bak >bibxelatex.tex
	fi
	rm bibxelatex.tex.bak

	TBIX=bibxelatex
	RBIX=

fi

if [ $RUNBIDI -eq 0 ]; then
	TBID=bidipoem
	RBID=
	echo "creating bidipoem.tex"
	# expected DejaVu font is Sans, which uses too much space
	# for the persian (the two parts of the line are offset)
	# and needs to be scaled down.
	POEMSCALE=
	echo $POEMFONT | grep DejaVu && POEMSCALE="[Scale=0.9]"
	cat bidipoem.in | sed "s/%POEMFONT%/$POEMSCALE{$POEMFONT}/" > bidipoem.tex
fi

# blended-circles test - does not work on older versions of TikZ.
if [ "$RUNBLC" = 0 ]; then
	TBLC=blended-circles
	RBLC=
fi

if [ $RUNCONTEXT -eq 0 ]; then
	TCON=context
	RCON=
fi

if [ $RUNLUALATEX -eq 0 ]; then
	echo "creating lualatex.tex"
	if [ -n "$CFONT" ] || [ -n "$JFONT" ] || [ -n "$KFONT" ]; then
		sed 's/GOOGLE/CJK example(s) from translate.google.com./' \
		 lualatex.in >lualatex.tex
	else
		sed 's/GOOGLE/CJK examples omitted./' lualatex.in >lualatex.tex
	fi
	# do not use sed -i, it might not be GNU sed
	cp lualatex.tex{,.bak}
	if [ -n "$CFONT" ]; then
		sed "s%CHINESE%$CFONT%" lualatex.tex.bak >lualatex.tex
	else
		sed 's/.*CHINESE.*/(Simplified Chinese omitted, no suitable font)/' \
		 lualatex.tex.bak >lualatex.tex
	fi
	cp lualatex.tex{,.bak}
	if [ -n "$JFONT" ]; then
		sed "s%JAPANESE%$JFONT%" lualatex.tex.bak >lualatex.tex
	else
		sed 's/.*JAPANESE.*/(Japanese omitted, no suitable font)/' \
		 lualatex.tex.bak >lualatex.tex
	fi
	cp lualatex.tex{,.bak}
	if [ -n "$KFONT" ]; then
		sed "s%KOREAN%$KFONT%" lualatex.tex.bak >lualatex.tex
	else
		sed 's/.*KOREAN.*/(Korean omitted, no suitable font)/' \
		 lualatex.tex.bak >lualatex.tex
	fi
	cp lualatex.tex{,.bak}
	sed "s%FONT%$MAINFONT%" lualatex.tex.bak >lualatex.tex
	rm lualatex.tex.bak

	TLUA=lualatex
	RLUA=
fi

if [ $RUNMOS -eq 0 ]; then
	TMOS=mosfet
	RMOS=
fi

if [ $RUNPAREN -eq 0 ]; then
	TPAR=paren
	RPAR=
	# here we need the path to match_parens
	PARFILE=$(type -pa match_parens)
else
	PARFILE=
fi

if [ $RUNXELATEX -eq 0 ]; then
	echo "creating xelatex.tex"
	sed "s%FONT%$MAINFONT%" xelatex.in  >xelatex.tex
	# as before, do not assume sed can do sed -i
	cp xelatex.tex{,.bak}
	if [ -n "$CFONT" ]; then
		sed "s%CHINESE%$CFONT%" xelatex.tex.bak >xelatex.tex
	else
		sed '/\\chinese/d' xelatex.tex.bak >xelatex.tex
	fi
	cp xelatex.tex{,.bak}
	if [ -n "$JFONT" ]; then
		sed "s%JAPANESE%$JFONT%" xelatex.tex.bak >xelatex.tex
	else
		sed '/\\japanese/d' xelatex.tex.bak >xelatex.tex
	fi
	cp xelatex.tex{,.bak}
	if [ -n "$KFONT" ]; then
		sed "s%KOREAN%$KFONT%" xelatex.tex.bak >xelatex.tex
	else
		sed '/\\korean/d' xelatex.tex.bak >xelatex.tex
	fi
	rm xelatex.tex.bak

	TXEL=xelatex
	RXEL=
fi

if [ $RUNXINDY -eq 0 ]; then
	echo "creating xindy.tex"
	sed "s%FONT%$MAINFONT%" xindy.in >xindy.tex
	TXIN=xindy
	RXIN=
fi

if [ $RUNXINDYBAS -eq 0 ]; then
	TXIB=xindynonlua
	RXIB=
fi

echo "creating Makefile"
cat Makefile.in | sed \
 -e "s/@TBID@/$TBID/" -e "s/@RBID@/$RBID/g" \
 -e "s/@TBIX@/$TBIX/" -e "s/@RBIX@/$RBIX/g" \
 -e "s/@TBLC@/$TBLC/" -e "s/@RBLC@/$RBLC/g" \
 -e "s/@TBLR@/$TBLR/" -e "s/@RBLR@/$RBLR/g" \
 -e "s/@TBLT@/$TBLT/" -e "s/@RBLT@/$RBLT/g" \
 -e "s/@TBLU@/$TBLU/" -e "s/@RBLU@/$RBLU/g" \
 -e "s/@TBTX@/$TBTX/" -e "s/@RBTX@/$RTBX/g" \
 -e "s/@TCON@/$TCON/" -e "s/@RCON@/$RCON/g" \
 -e "s/@TCYL@/$TCYL/" -e "s/@RCYL@/$RCYL/g" \
 -e "s/@TLUA@/$TLUA/" -e "s/@RLUA@/$RLUA/g" \
 -e "s/@TMOS@/$TMOS/" -e "s/@RMOS@/$RMOS/g" \
 -e "s/@TPDF@/$TPDF/" -e "s/@RPDF@/$RPDF/g" \
 -e "s/@TPAR@/$TPAR/" -e "s/@RPAR@/$RPAR/g" \
 -e "s/@TTRI@/$TTRI/" -e "s/@RTRI@/$RTRI/g" \
 -e "s/@TXIN@/$TXIN/" -e "s/@RXIN@/$RXIN/g" \
 -e "s/@TXIB@/$TXIB/" -e "s/@RXIB@/$RXIB/g" \
 -e "s/@TXEL@/$TXEL/" -e "s/@RXEL@/$RXEL/g" \
 -e "s%@PARFILE@%$PARFILE%" \
 >Makefile

echo "latex-test $VERSION is now configured for your system."
if [ -n "$BADPARM" ]; then
	echo "unrecognized parameter(s) $BADPARM"
fi
# finish by noting if some things will not be run
if [ $WARNINGS -ne 0 ]; then
	echo "There were $WARNINGS warning(s)"
fi
if [ $WARNINGS -ne 0 ] || [ -n "$BADPARM" ]; then
	echo "please review before continuing"
else
	echo "you can now run 'make'"
fi

