1#!/bin/bash
2
3export LC_ALL=C
4
5tmpdir="$(mktemp -d)"
6src="$PWD"
7rc=0
8
9cp ../../{rgbfix,contrib/gbdiff.bash} "$tmpdir"
10cd "$tmpdir"
11trap "cd; rm -rf '$tmpdir'" EXIT
12
13bold="$(tput bold)"
14resbold="$(tput sgr0)"
15red="$(tput setaf 1)"
16green="$(tput setaf 2)"
17rescolors="$(tput op)"
18
19RGBFIX=./rgbfix
20
21tryDiff () {
22	if ! diff -u --strip-trailing-cr "$1" "$2"; then
23		echo "${bold}${red}${3:-$1} mismatch!${rescolors}${resbold}"
24		false
25	fi
26}
27
28tryCmp () {
29	if ! cmp "$1" "$2"; then
30		./gbdiff.bash "$1" "$2"
31		echo "${bold}${red}${3:-$1} mismatch!${rescolors}${resbold}"
32		false
33	fi
34}
35
36runTest () {
37	flags="$(head -n 1 "$2/$1.flags")" # Allow other lines to serve as comments
38
39	for variant in '' ' piped'; do
40		our_rc=0
41		if [[ $progress -ne 0 ]]; then
42			echo "${bold}${green}$1${variant}...${rescolors}${resbold}"
43		fi
44		if [[ -z "$variant" ]]; then
45			cp "$2/$1.bin" out.gb
46			if [[ -n "$(eval $RGBFIX $flags out.gb '2>out.err')" ]]; then
47				echo "${bold}${red}Fixing $1 in-place shouldn't output anything on stdout!${rescolors}${resbold}"
48				our_rc=1
49			fi
50			subst='out.gb'
51		else
52			# Stop! This is not a Useless Use Of Cat. Using cat instead of
53			# stdin redirection makes the input an unseekable pipe - a scenario
54			# that's harder to deal with.
55			cat "$2/$1.bin" | eval $RGBFIX "$flags" '>out.gb' '2>out.err'
56			subst='<stdin>'
57		fi
58
59		sed "s/$subst/<filename>/g" "out.err" | tryDiff "$2/$1.err" - "$1.err${variant}"
60		our_rc=$(($? || $our_rc))
61		if [[ -r "$2/$1.gb" ]]; then
62			tryCmp "$2/$1.gb" "out.gb" "$1.gb${variant}"
63			our_rc=$(($? || $our_rc))
64		fi
65
66		rc=$(($rc || $our_rc))
67		if [[ $our_rc -ne 0 ]]; then break; fi
68	done
69}
70
71rm -f padding*_* # Delete padding test cases generated but not deleted (e.g. interrupted)
72
73progress=1
74for i in "$src"/*.bin; do
75	runTest "$(basename "$i" .bin)" "$src"
76done
77
78# Check the result with all different padding bytes
79echo "${bold}Checking padding...${resbold}"
80cp "$src"/padding{,-large,-larger}.bin .
81touch padding{,-large,-larger}.err
82progress=0
83for b in {0..254}; do
84	printf "\r$b..."
85	for suffix in '' -large -larger; do
86		cat <<<'-p $b' >padding$suffix.flags
87		tr '\377' \\$(($b / 64))$((($b / 8) % 8))$(($b % 8)) <"$src/padding$suffix.gb" >padding$suffix.gb # OK because $FF bytes are only used for padding
88		runTest padding${suffix} .
89	done
90done
91printf "\rDone! \n"
92
93# TODO: check MBC names
94
95# Check that RGBFIX errors out when inputting a non-existent file...
96$RGBFIX noexist 2>out.err
97rc=$(($rc || $? != 1))
98tryDiff "$src/noexist.err" out.err noexist.err
99rc=$(($rc || $?))
100
101exit $rc
102