#!/bin/bash
# Called as one of
#   $0 (dryrun|pdftex|xetex|luatex) ... '\input <job>.jam'
#   $0 (dryrun|pdftex|xetex|luatex) ... '\input <job>.sh.jam'
#   $0 dryrun ... '\input <job>.sh'
#   $0 /path/a.tex
# The `$0 dryrun ... '\input job[.sh].jam'` calls set the latex engine to $0,
# accounting for the `$0 /path/a.tex` call.
# The `$0 dryrun ... '\input job.sh'` calls just source job.sh 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 sourced 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
job=${in%.*}
out="$job.pdf"
dir="$job.d/$1"

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

# 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}'\'
	;;
dryrun)
	latex=$(realpath "$0")
	case "$in" in
		*.sh) source "$in" | sed "s=$testdir=<TESTDIR>=g" >"$job.dryrun.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
pdfjam="./pdfjam --latex '$latex' --vanilla --builddir '$dir' --outfile '$out'$preamble"

# Evaluate .jam files
case "$job" in
	*.sh) source "$in" ;;
	*) eval "$pdfjam $(< "$in")" ;;
esac

[ "$1" = dryrun ] && 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"
