#!/bin/sh

cd "$(dirname "$0")/../../../.." || exit 1

while [ "$#" -gt 0 ]; do
	case "$1" in
		--diff)
			from_commitish=$2
			shift
			;;
		--from)
			from_commitish=$2
			shift
			;;
		--to)
			to_commitish=$2
			shift
			;;
		-j*) ;;
		--lfs-pull)
			lfs_pull=true
			;;
		*)
			printf "Unknown option: %s\n\n" "$1"
			exit 1
			;;
	esac
	shift
done

# The PNG contents are checked from the working tree, so it must match the
# upper end of the checked range.
if [ -n "${to_commitish}" ]; then
	git checkout --quiet "${to_commitish}" || exit 1
fi

file_list=$(mktemp) || exit 1
trap 'rm -f "${file_list}"' EXIT

if [ -n "${from_commitish}" ]; then
	if ! git rev-parse --verify --quiet "${from_commitish}^{commit}" >/dev/null; then
		printf "Cannot find base commit: %s\n" "${from_commitish}"
		exit 1
	fi
	if [ -n "${to_commitish}" ]; then
		to_ref="${to_commitish}"
	else
		to_ref="$(git rev-parse HEAD)"
	fi
	if ! merge_base=$(git merge-base "${from_commitish}" "${to_ref}" 2>/dev/null); then
		printf "Cannot find merge base between %s and %s.\n" "${from_commitish}" "${to_ref}"
		exit 1
	fi
	diff="${merge_base}..${to_ref}"
	printf "Running pngcheck for range\n%s\n\n" "${diff}"
	if ! git diff --name-only --diff-filter=AM --no-renames "${diff}" -- '*.png' >"${file_list}"; then
		echo "git diff failed."
		exit 1
	fi
else
	echo "WARNING: running pngcheck without base commit, likely not what you want."
	find binaries/data/mods -name '*.png' >"${file_list}"
fi

if [ ! -s "${file_list}" ]; then
	echo "No PNG file to check."
	exit 0
fi

has_errors=false

while read -r file; do
	if [ ! -f "${file}" ]; then
		printf "%s: file not found\n" "${file}"
		has_errors=true
		continue
	fi

	# PNGs are stored in LFS, their content must be available to check them.
	if grep -q "^version https://git-lfs" "${file}"; then
		if [ "${lfs_pull}" = true ]; then
			# CI opt-in: fetch just this file's content on demand.
			git lfs pull -I "${file}"
		fi
		if grep -q "^version https://git-lfs" "${file}"; then
			printf "%s: stored as an LFS pointer, run 'git lfs pull' before checking\n" "${file}"
			has_errors=true
			continue
		fi
	fi

	if ! output=$(pngcheck "${file}" 2>&1); then
		printf "%s\n" "${output}"
		has_errors=true
	elif printf "%s\n" "${output}" | grep -qiE "(warning|error):"; then
		# Report problems that pngcheck logs as warnings but exits 0 for.
		printf "%s\n" "${output}"
		has_errors=true
	fi
done <"${file_list}"

if [ "${has_errors}" = true ]; then
	exit 1
fi
