#!/bin/sh
# SPDX-FileCopyrightText: Peter Pentchev <roam@ringlet.net>
# SPDX-License-Identifier: BSD-2-Clause

set -e

: "${DEFAULT_IMAGE:=confget:c7}"

unset tempd

cleanup()
{
	echo 'Cleaning up if necessary'

	if [ -n "$tempd" ]; then
		echo "Removing the $tempd temporary directory"
		rm -rf -- "$tempd"
	fi

	echo 'Done cleaning up'
}

usage()
{
	cat <<"EOUSAGE"
Usage:	tox.sh [-i docker-image]
	tox.sh -h | --help | -V | --version

	-h	display program usage information and exit
	-i	specify the Docker image to use (default: '$DEFAULT_IMAGE')
	-V	display program version information and exit
EOUSAGE
}

img="$DEFAULT_IMAGE"
unset show_help show_version

while getopts 'hi:V-:' o; do
	case "$o" in
		h)
			show_help=1
			;;

		i)
			img="$OPTARG"
			;;

		V)
			show_version=1
			;;

		-)
			case "$OPTARG" in
				help)
					show_help=1
					;;

				version)
					show_version=1
					;;

				*)
					echo "Invalid long option '$OPTARG' specified" 1>&2
					usage 1>&2
					exit 1
					;;
			esac
			;;

		*)
			usage 1>&2
			exit 1
			;;
	esac
done
[ -z "$show_version" ] || version
[ -z "$show_help" ] || usage
[ -z "$show_version$show_help" ] || exit 0

shift $((OPTIND - 1))
if [ "$#" -gt 0 ]; then
	usage 1>&2
	exit 1
fi

trap cleanup EXIT HUP INT TERM QUIT
tempd="$(mktemp -d -t confget-test.XXXXXX)"
echo "Using $tempd as a temporary directory"

echo 'Figuring out where the Git checkout root is'
git worktree list --porcelain > "$tempd/worktree.txt"
git_root="$(awk '$1 == "worktree" { print $2; exit }' "$tempd/worktree.txt")"
if [ ! -d "$git_root" ] || [ ! -f "$git_root/Makefile" ]; then
	echo "Could not detect the Git checkout root directtory, got '$git_root'" 1>&2
	exit 1
fi
echo "Using $git_root as the Git checkout root directory"

tempconf="$tempd/confget"
mkdir -- "$tempconf"

cd -- "$git_root"
echo "Copying the files that Git knows about into $tempconf"
git ls-files -z > "$tempd/ls-files.txt"
tar -cf "$tempd/confget.tar" --null -T "$tempd/ls-files.txt"
tar -xvf "$tempd/confget.tar" -C "$tempconf"
if [ ! -f "$tempconf/Makefile" ]; then
	echo "Could not copy the confget source tree into $tempconf" 1>&2
	exit 1
fi

echo "Checking the Tox version in the $img container"
docker run \
	--rm \
	-- \
	"$img" \
	/opt/confget-tox/bin/python3 \
		-m pip \
		list \
		--format=columns > "$tempd/pip-list.txt"
if grep -Eqe '^tox[[:space:]]+3\.' -- "$tempd/pip-list.txt"; then
	echo 'Applying the "back to Tox 3 format" patch'
	patch -- "$tempd/confget/python/tox.ini" < "$tempd/confget/test-docker/data/fixup/back-to-tox-3.patch"
fi

echo "Starting a $img container"
docker run \
	--rm \
	-v "$tempd:/opt/confget-temp:ro" \
	-- \
	"$img" \
	/opt/confget-tox/bin/tox \
		-c /opt/confget-temp/confget/python/tox.ini \
		--workdir /tmp/confget-tox-run \
		-e unit-tests,prove
