#!/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 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)
# 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
TESTBIDIPOEM=yes
TESTCONTEXT=yes
TESTLUALATEX=yes
TESTRUBY=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" = "bidipoem" ]; then
		TESTBIDIPOEM=
	elif [ "$PARM" = "context" ]; then
		TESTCONTEXT=
	elif [ "$PARM" = "lualatex" ]; then
		TESTLUALATEX=
	elif [ "$PARM" = "ruby" ]; then
		TESTRUBY=
	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), $2 is the name known to fontconfig. 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.
#
# 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
if [ $# -ne 2 ]; 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
		echo -n "$2"
	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
}

# main line

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

ERRORS=0
WARNINGS=0

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

echo -n "Checking for cat   ... "
CAT=$(type -pa cat)
if [ -n "$CAT" ]; then
	echo $CAT
else
	echo "no"
	let ERRORS=$ERRORS+1
fi

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

echo -n "Checking for grep  ... "
GREP=$(type -pa grep)
if [ -n "$GREP" ]; then
	echo $GREP
else
	echo "no"
	let ERRORS=$ERRORS+1
fi

echo -n "Checking for make  ... "
MAKE=$(type -pa make)
if [ -n "$MAKE" ]; then
	echo $MAKE
else
	echo "no"
	let ERRORS=$ERRORS+1
fi

echo -n "Checking for rm    ... "
RM=$(type -pa rm)
if [ -n "$RM" ]; then
	echo $RM
else
	echo "no"
	let ERRORS=$ERRORS+1
fi

echo -n "Checking for sed   ... "
SED=$(type -pa sed)
if [ -n "$SED" ]; then
	echo $SED
else
	echo "no"
	let ERRORS=$ERRORS+1
fi

echo -n "Checking for touch ... "
TOUCH=$(type -pa touch)
if [ -n "$TOUCH" ]; then
	echo $TOUCH
else
	echo "no"
	let ERRORS=$ERRORS+1
fi

# now check X is minimally present, plus fontconfig
echo -n "Checking for X       ... "
XORG=$(type -pa X)
if [ -n "$XORG" ]; then
	echo $XORG
else
	echo "no"
	let ERRORS=$ERRORS+1
fi

if [ $WARNINGS -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 from poppler to check if xindy works"
	echo "and YOU will need a PDF viewer"
	exit 1
else
	echo "I hope you have a PDF viewer"
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 TeX components - give up if pdflatex is missing.
echo "checking TeX programs"

echo -n "Checking for pdflatex     ... "
PDFLATEX=$(type -pa pdflatex)
if [ -n "$PDFLATEX" ]; then
	echo $PDFLATEX
else
	echo "no"
	echo "ERROR: you need TeX and LaTeX to run any of these tests"
	echo "perhaps your PATH is wrong ?"
	exit 1
fi

# asy and (for the moment) biber only require latex
if [ -n "$TESTASY" ]; then
	echo -n "Checking for asy          ... "
	ASY=$(type -pa asy)
	if [ -n "$ASY" ]; then
		echo $ASY
	else
		echo "no"
		echo "WARNING: You need asy to run the asy (drawing) test"
		let WARNINGS=$WARNINGS+1
	fi
else
	echo "asy deselected by request"
fi

if [ -n "$TESTBIBER" ]; then
	echo -n "Checking for biber        ... "
	BIBER=$(type -pa biber)
	if [ -n "$BIBER" ]; then
		echo $BIBER
	else
		echo "no"
		echo "WARNING: You need biber to run the biber (bibliography) test"
		let WARNINGS=$WARNINGS+1
	fi
else
	echo "biber deselected by request"
fi

if [ -n "$TESTLUALATEX" ]; then
	echo -n "Checking for lualatex     ... "
	LUALATEX=$(type -pa lualatex)
	if [ -n "$LUALATEX" ]; then
		echo $LUALATEX
	else
		echo "no"
		echo "WARNING: You need LuaLaTeX to run context and xindy tests"
		let WARNINGS=$WARNINGS+1
	fi
	echo -n "Checking for luaotfload-tool "
	LUAOTFLOADTOOL=$(type -pa luaotfload-tool)
	if [ -n "$LUAOTFLOADTOOL" ]; then
		echo $LUAOTFLOADTOOL
	else
		echo "no"
		echo "WARNING: luaotfload-tool not found, fontspec might not find fonts"
		let WARNINGS=$WARNINGS+1
	fi
	if [ -n "$TESTXINDY" ]; then
		echo -n "Checking for makeglossarises "
		MAKEGLOSSARIES=$(type -pa makeglossaries)
		if [ -n "$MAKEGLOSSARIES" ]; then
			echo $MAKEGLOSSARIES
		else
			echo "no"
			echo "WARNING: You need makeglossaries to run the xindy tests"
			let WARNINGS=$WARNINGS+1
		fi

		if [ -n "$MAKEGLOSSARIES" ]; then
			echo -n "Checking for xindy        ... "
			XINDY=$(type -pa xindy)
			if [ -n "$XINDY" ]; then
				echo $XINDY
				echo -n "Checking for pdfinfo ... "
				PDFINFO=$(type -pa pdfinfo)
				if [ -n "$PDFINFO" ]; then
					echo $PDFINFO
				else
					echo "no"
					echo "WARNING: You need pdfinfo to run the xindy tests"
					let WARNINGS=$WARNINGS+1
				fi
			else
				echo "no"
				echo "WARNING: You need xindy to run the xindy tests"
				let WARNINGS=$WARNINGS+1
			fi
		fi

	else
		echo "xindy deselected by request"
	fi

	if [ -n "$TESTCONTEXT" ]; then
		# context MkIV uses luatex
		echo -n "Checking for context      ... "
		CONTEXT=$(type -pa context)
		if [ -n "$CONTEXT" ]; then
			echo $CONTEXT
			# 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
		else
			echo "no"
			echo "WARNING: You need ConTeXt to run the context test"
			let WARNINGS=$WARNINGS+1
		fi
	else
		echo "context deselected by request"
	fi
fi

# xindynonlua can be run without lualatex / fonts
# for the moment, this is a messy repeat of some tests
# if lualatex was found
if [ -n "$TESTXINDYNONLUA" ]; then
	echo "looking for deps for xindynonlua test"
	if [ -z "$MAKEGLOSSARIES" ]; then
		echo -n "Checking for makeglossarises "
		MAKEGLOSSARIES=$(type -pa makeglossaries)
		if [ -n "$MAKEGLOSSARIES" ]; then
			echo $MAKEGLOSSARIES
		else
			echo "no"
			echo "WARNING: You need makeglossaries to run the xindynonlua test"
			let WARNINGS=$WARNINGS+1
		fi
		if [ -n "$MAKEGLOSSARIES" ]; then
			echo -n "Checking for xindy        ... "
			XINDY=$(type -pa xindy)
			if [ -n "$XINDY" ]; then
				echo $XINDY
				echo -n "Checking for pdfinfo ... "
				PDFINFO=$(type -pa pdfinfo)
				if [ -n "$PDFINFO" ]; then
					echo $PDFINFO
				else
					echo "no"
					echo "WARNING: You need pdfinfo to run the xindynonlua test"
					let WARNINGS=$WARNINGS+1
				fi
			else
				echo "no"
				echo "WARNING: You need xindy to run the xindy tests"
				let WARNINGS=$WARNINGS+1
			fi
		fi
	fi
fi

if [ -n "$TESTXELATEX" ]; then
	echo -n "Checking for xelatex      ... "
	XELATEX=$(type -pa xelatex)
	if [ -n "$XELATEX" ]; then
		echo $XELATEX
	else
		echo "no"
		echo "WARNING: You need XeLaTeX to run some tests"
		let WARNINGS=$WARNINGS+1
	fi
else
	echo "xelatex deselected by request"
fi

# do ruby last, all the other tests will complete without it
# being present!
if [ -n "$TESTRUBY" ]; then
	echo -n "checking for ruby         ... "
	RUBY=$(type -pa ruby)
	if [ -n "$RUBY" ]; then
		echo $RUBY

		echo -n "Checking for match_parens... "
		MATCHPARENS=$(type -pa match_parens)
		if [ -n "$MATCHPARENS" ]; then
			echo $MATCHPARENS
		else
			echo "no"
			echo "WARNING: You need match_parens to test ruby"
			let WARNINGS=$WARNINGS+1
		fi
	else
		echo "no"
		echo "WARNING: cannot test ruby"
		let WARNINGS=$WARNINGS+1
	fi
else
	echo "ruby deselected by request"
fi

if [ $WARNINGS -eq 0 ]; then
	echo "your TeX kit appears to be complete"
fi

echo "Checking for useful TTF/OTF fonts for lualatex, xelatex, xindy"
# 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
	if [ -n "$LUALATEX" ] || [ -n "$XELATEX" ]; then
	echo "looking to see if I can search for texlive fonts"
		echo -n "Checking for kpsepath     ... "
		KPSEPATH=$(type -pa kpsepath)
		if [ -n "$KPSEPATH" ]; then
			echo $KPSEPATH
		else
			echo "no"
			echo "I need kpsepath to find texlive fonts"
		fi
		echo -n "Checking for tr           ... "
		TR=$(type -pa tr)
		if [ -n "$TR" ]; then
			echo $TR
		else
			echo "no"
			echo "I need tr to find texlive 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"
	echo -n "Checking for fc-list ... "
	FCLIST=$(type -pa fc-list)
	if [ -n "$FCLIST" ]; then
		echo $FCLIST
	else
		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
	# NB when the Name is specified (instead of the filename), do NOT use
	# sysfont.
	test -n "$FCLIST" && fc-list 2>/dev/null | grep -q "$MAINFONT"
	if [ $? -ne 0 ]; then
		echo "ERROR: specified main font $MAINFONT not found"
		exit 1
	else
		echo "will use specified font $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 'DejaVu Serif')
	test -z "$MAINFONT" && MAINFONT=$(sysfont FreeSerif.otf 'FreeSerif')

	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
	test -n "$FCLIST" && fc-list 2>/dev/null | grep -q "$CFONT"
	if [ $? -ne 0 ]; 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 fireflysung
	# is very old and might not be simplified, so prefer Kai (script) to that
        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 'AR PL UMing CN')
	    test -z "$CFONT" && CFONT=$(sysfont gbsn00lp.ttf 'AR PL SungtiL GB')
	    test -z "$CFONT" && CFONT=$(sysfont fireflysung.ttf 'AR PL New Sung')
	    # now try Kai (script)
	    test -z "$CFONT" && CFONT=$(sysfont ukai.ttc 'AR PL UKai CN')
	    test -z "$CFONT" && CFONT=$(sysfont gkai00mp.ttf 'AR PL KaitiM GB')
	    test -z "$CFONT" && CFONT=$(sysfont odokai.ttf 'AR PL New Kai')
	    # now try Hei (sans)
	    test -z "$CFONT" && CFONT=$(texfont FandolHei-Regular.otf)
	    test -z "$CFONT" && CFONT=$(sysfont wqy-zenhei.ttc 'WenQuanYi Zen Hei')
	    # the version of Droid Sans that includes Chinese and Japanese
	    test -z "$CFONT" && CFONT=$(sysfont DroidSansFallbackFull.ttf 'Droid Sans Fallback')
            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
	test -n "$FCLIST" && fc-list 2>/dev/null | grep -q "$JFONT"
	if [ $? -ne 0 ]; 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 'IPAexMincho')
	    # repeat for the older, no longer maintained, variants
	    test -z "$JFONT" && JFONT=$(texfont ipam.ttf)
	    test -z "$JFONT" && JFONT=$(sysfont ipam.ttf 'IPAMincho')
	    # try kochi
	    test -z "$JFONT" && JFONT=$(sysfont kochi-mincho-subst.ttf 'Kochi Mincho')
	    # then try gothic (sans)
	    # again, try ipaex before ipa
	    test -z "$JFONT" && JFONT=$(texfont ipaexg.ttf)
	    test -z "$JFONT" && JFONT=$(sysfont ipaexg.ttf 'IPAexGothic')
	    test -z "$JFONT" && JFONT=$(texfont ipag.ttf)
	    test -z "$JFONT" && JFONT=$(sysfont ipag.ttf 'IPAGothic')
	    # then try vlgothic which is currently maintained
	    test -z "$JFONT" && JFONT=$(sysfont VL-Gothic-Regular.ttf 'VL Gothic')
	    test -z "$JFONT" && JFONT=$(sysfont kochi-gothic-subst.ttf 'Kochi Gothic' )
	    # try pan-unicode fonts as a fallback (i.e. chinese, but they do cover japanese)
	    test -z "$JFONT" && JFONT=$(sysfont wqy-zenhei.ttc 'WenQuanYi Zen Hei')
	    test -z "$JFONT" && JFONT=$(sysfont DroidSansFallbackFull.ttf 'Droid Sans Fallback')
            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
	test -n "$FCLIST" && fc-list 2>/dev/null | grep -q "$KFONT"
	if [ $? -ne 0 ]; 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 'Baekmuk Batang')
	    test -z "$KFONT" && KFONT=$(sysfont NanumMyeongjo-Regular.ttf 'NanumMyeongjo')
	    # sans
	    test -z "$KFONT" && KFONT=$(sysfont dotum.ttf 'Baekmuk Dotum')
	    test -z "$KFONT" && KFONT=$(sysfont gulim.ttf 'Baekmuk Gulim')
	    test -z "$KFONT" && KFONT=$(sysfont NanumGothic-Regular.ttf 'NanumGothic')
	    # pan-unicode
	    test -z "$KFONT" && KFONT=$(sysfont wqy-zenhei.ttc 'WenQuanYi Zen Hei')
            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 "$TESTXELATEX" ] && [ -n "$TESTBIDIPOEM" ]; then
    if [ -n "$OMFONT" ]; 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 is supplied with texlive
	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 'FreeSerif')
	# similarly, DejaVu Sans might be from texlive or system
	test -z "$POEMFONT" && POEMFONT=$(texfont DejaVuSans.ttf)
	test -z "$POEMFONT" && POEMFONT=$(sysfont DejaVuSans.ttf 'DejaVu Sans')
	if [ -n "$POEMFONT" ]; then
		echo $POEMFONT
	else
		TESTBIDIPOEM=
		echo "no suitable font found, cannot test bidipoem"
	fi
    fi
fi

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

# the latex test will always run if we got this far.
echo ' pdflatex can be tested'

# asy depends on asy as well as latex
if [ -n "$ASY" ]; then
	echo ' asy can be tested'
	RUNASY=1
else
	echo ' asy will not be tested'
	RUNASY=0
fi

# biber - for the moment, this uses latex
if [ -n "$BIBER" ]; then
	RUNBIBER=1
	echo ' biber can be tested'
else
	RUNBIBER=0
	echo ' biber will not be tested'
fi

# context apparently only needs latex
if [ -n "$CONTEXT" ]; then
	RUNCONTEXT=1
	echo ' context can be tested'
else
	RUNCONTEXT=0
	echo ' context will not be tested'
fi

# lualatex depends on LUALATEX, MAINFONT
# and for complete coverage CFONT JFONT KFONT
if [ -n "$LUALATEX" ] && [ -n "$MAINFONT" ]; then
	RUNLUALATEX=1
	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
	RUNLUALATEX=0
	echo ' lualatex will not be tested'
fi

# xindy - uses lualatex, mainfont and makeglossaries, needs pdfinfo to see if it worked
if [ -n "$XINDY" ] && [ -n "$LUALATEX" ] && [ -n "$MAINFONT" ] && [ -n "$MAKEGLOSSARIES" ] && [ -n "$PDFINFO" ]; then
	RUNXINDY=1
	echo ' xindy can be tested'
else
	RUNXINDY=0
	echo ' xindy will not be tested'
fi

# basic xindy test (xindynonlua) only needs xindy, makeglossaries, pdfinfo
if [ -n "$XINDY" ] && [ -n "$MAKEGLOSSARIES" ] && [ -n "$PDFINFO" ]; then
	RUNXINDYBAS=1
	echo ' xindynonlua can be tested'
else
	RUNXINDYBAS=0
	echo ' xindynonlua will not be tested'
fi


# explicitly initialise this, so it has 0 unless all deps exist.
# other RUN variables are explicitly tested for on their own.
RUNBIBXELATEX=0

# xelatex depends on XELATEX, MAINFONT
# and for complete coverage CFONT JFONT KFONT
# and bidipoem uses xelatex
if [ -n "$XELATEX" ] && [ -n "$MAINFONT" ]; then
	RUNXELATEX=1
	if [ -n "$CFONT" ] && [ -n "$JFONT" ] && [ -n "$KFONT" ]; then
		XELMSG="completely"
	else
		XELMSG="but not for all CJK languages"
	fi
	echo " xelatex can be tested $LUAMSG"

	# bibxelatex needs BIBER and both CFONT AND JFONT
	if [ -n "$BIBER" ] && [ -n "$CFONT" ] && [ -n "$JFONT" ]; then
		if [ -n "$KFONT" ]; then
			echo " bibxelatex can be tested"
		else
			echo " bibxelatex can be tested, but without korean"
		fi
		RUNBIBXELATEX=1
	else
		echo " bibxelatex requires biber plus both a chinese and a japanese font"
	fi
else
	RUNXELATEX=0
	echo ' xelatex, bibxelatex and bidipoem will not be tested'
fi

# bidipoem does not use MAINFONT, so test its deps separately
if [ -n "$XELATEX" ] && [ -n "$TESTBIDIPOEM" ]; then
	echo " bidipoem can be tested"
	RUNBIDI=1
else
	echo " bidipoem will not be tested"
	RUNBIDI=0
fi

# ruby depends on MATCHPARENS
if [ -n "$RUBY" ] && [ -n "$MATCHPARENS" ]; then
	RUNRUBY=1
	echo " ruby can be tested"
else
RUNRUBY=0
	echo " ruby will not be tested"
fi

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

# targets on which all: depends
TASY=
TBIB=
TBID=
TBIX=
TCON=
TLUA=
TPAR=
TXIN=
# ?XIB 'xindy basic' actually runs xindynonlua
# so put if after xindy
TXIB=
TXEL=

# convert actual rules to # or uncommented
RASY=#
RBIB=#
RBIX=#
RBID=#
RCON=#
RLUA=#
RPAR=#
RXIN=#
RXIB=#
RXEL=#

if [ $RUNASY -eq 1 ]; then
	TASY=asy
	RASY=
fi

if [ $RUNBIBER -eq 1 ]; then
	TBIB=biblatex
	RBIB=
fi

if [ $RUNBIDI -eq 1 ]; 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

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

if [ $RUNLUALATEX -eq 1 ]; 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 [ $RUNXINDY -eq 1 ]; then
	echo "creating xindy.tex"
	sed "s%FONT%$MAINFONT%" xindy.in >xindy.tex
	TXIN=xindy
	RXIN=
fi

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

if [ $RUNRUBY -eq 1 ]; then
	TPAR=paren
	RPAR=
	PARFILE="$MATCHPARENS"
else
	PARFILE=
fi

if [ $RUNXELATEX -eq 1 ]; 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 [ $RUNBIBXELATEX -eq 1 ]; 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' ibibxelatex.tex.bak >bibxelatex.tex
	fi
	rm bibxelatex.tex.bak

	TBIX=bibxelatex
	RBIX=

fi

echo "creating Makefile"
cat Makefile.in | sed \
 -e "s/@TASY@/$TASY/" -e "s/@RASY@/$RASY/g" \
 -e "s/@TBIB@/$TBIB/" -e "s/@RBIB@/$RBIB/g" \
 -e "s/@TBIX@/$TBIX/" -e "s/@RBIX@/$RBIX/g" \
 -e "s/@TBID@/$TBID/" -e "s/@RBID@/$RBID/g" \
 -e "s/@TCON@/$TCON/" -e "s/@RCON@/$RCON/g" \
 -e "s/@TLUA@/$TLUA/" -e "s/@RLUA@/$RLUA/g" \
 -e "s/@TPAR@/$TPAR/" -e "s/@RPAR@/$RPAR/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 "tex-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

