#!/bin/bash
# Called as one of
#   $0 (xsh|pdftex|xetex|luatex) ... '\input <job>.jam'
#   $0 (xsh|pdftex|xetex|luatex) ... '\input <job>.sh.jam'
#   $0 xsh ... '\input <job>.sh'
#   $0 /path/a.tex
# The `$0 xsh ... '\input job[.sh].jam'` calls (with xsh being the name of a shell)
# set the latex engine to $0, accounting for the `$0 /path/a.tex` call.
# The `$0 xsh ... '\input job.sh'` calls just run job.sh in xsh and record the output.
# The `$0 engine ... '\input job[.sh].jam'` calls have pdfjam run the appropriate engine
# and output to $dir=job[.sh].d/engine.
# A .jam file just contains pdfjam options.
# A .sh.jam file is run in a shell and should make use of $pdfjam to produce output;
# it may also use $job=job.sh and $dir=$job.d/engine.

in=${!##\\input } # ${!#} is the last argument
export job=${in%.*}
out="$job.pdf"
export dir="$job.d/$1"

testdir=$(realpath -- "$(dirname "$0")")
basedir=$(realpath -- "$testdir/..")
export PATH="$basedir/bin:$testdir"
SH=sh

# Choose operation mode, set variables for setting pdfjam
case "$1" in
pdftex|xetex|luatex)
	latex=$(command -v "${1%tex}latex") \
		|| { echo Command "'${1%tex}latex'" not found; exit 1; }
	preamble=" --preamble '"'\input{regression-test.tex}\AtBeginDocument{\START}'\'
	;;
sh|bash|ksh|zsh)
	SH="$1"
	latex=$(realpath "$0")
	case "$in" in
		*.sh) "$SH" "$in" | sed "s=$basedir=\$BUILDDIR=g" >"$job.$1.log"; exit ;;
		*.jam) ;;
		*) echo "Wrong usage of $0"; exit 1 ;;
	esac
	;;
*/a.tex|a.tex)
	cp --verbose -- "$in" "$out"
	exit
	;;
*) echo "Unknown engine '$1'"; exit 1 ;;
esac
export pdfjam="./pdfjam --latex '$latex' --vanilla --builddir '$dir' --outfile '$out'$preamble"

# Evaluate .jam files
case "$job" in
	*.sh) "$SH" "$in" ;;
	*) "$SH" -c "$pdfjam $(< "$in")" ;;
esac

[ -z "${1##*sh}" ] && exit

# Rewrite log

<"$dir/a.log" awk 'BEGIN{s=0}
/^ *\[[0-9]/{ORS=""}
/]$/{ORS="\n"}
/] *\(/&&ORS=""{s=1}
/\)/&&s=1{s=0;ORS="\n"}
/^END-TEST-LOG$/{system("TZ=UTC pdfinfo '"$dir/a.pdf"'")}
//' \
	| sed '/^ *\[[0-9]/s/ //g
		s/\.\([0-9]\{3\}\)[0-9]*pt/.\1pt/g
		s/luatex\.def/pdftex.def/
		/^<[A-Za-z0-9_-]\+\.pdf,/s/id=[0-9]*/id=00/
		s/^\((epstopdf) *date: \)....-..-.. ..:..:..$/\1....-..-.. ..:..:../
		s/^\((epstopdf) *size: \|File size:       \)[0-9]\{4,\} bytes\(\.\?\)$/\10000 bytes\2/
		s/^\(Producer:        \).*$/\1TeXengine/
		' \
	>"$job.log"
