#!/bin/sh

trap '[ "$?" -ne 0 ] && printf "\nAn error occurred\n"' EXIT

verbose=0
start_index=0
end_index=0
# Dont' run this command as sudo.
if [ "$(id -u)" -eq 0 ]; then
	printf >&2 "Running %s as sudo is not supported.\n" "${0}"
	printf >&2 "Please check the documentation on:\n"
	printf >&2 "\tman distrobox-compatibility\t"
	printf >&2 "or consult the documentation page on:\n"
	printf >&2 "\thttps://github.com/89luca89/distrobox/blob/main/docs/compatibility.md\n"
	exit 1
fi

# Print usage to stdout.
# Arguments:
#   None
# Outputs:
#   print usage with examples.
show_help() {
	cat << EOF
Usage:

	compatibility-test [--index X]

Options:

	--start-index/si:		from which index image to start [default=0]
	--end-index/ei:		from which index image to start [default=last]
	--help/-h:		show this message
	--verbose/-v:		show more verbosity

EOF
}

# Parse arguments
while :; do
	case $1 in
		-h | --help)
			# Call a "show_help" function to display a synopsis, then exit.
			show_help
			exit 0
			;;
		-v | --verbose)
			shift
			verbose=1
			;;
		-si | --start-index)
			if [ -n "$2" ]; then
				start_index="$2"
				shift
				shift
			fi
			;;
		-ei | --end-index)
			if [ -n "$2" ]; then
				end_index="$2"
				shift
				shift
			fi
			;;
		*) # Default case: If no more options then break out of the loop.
			break ;;
	esac
done

set -o errexit
set -o nounset
# set verbosity
if [ "${verbose}" -ne 0 ]; then
	set -o xtrace
fi

image_list=$(grep -E "docker.io|quay.io|ghcr|registry.|ecr." "$(dirname "${0}")"/../docs/compatibility.md |
	cut -d'|' -f 4 | sed 's/<br>/\n/g' | tr -d ' ' | tail -n +2)
if [ "${end_index}" -eq 0 ]; then
	end_index=$(echo "${image_list}" | wc -l)
fi

progress=1
for image in ${image_list}; do
	# POSIX SH does not support C-style loops, let's check boundaries manually.
	if [ "${progress}" -lt "${start_index}" ]; then
		# increase counter
		progress=$((progress + 1))
		continue
	elif [ "${progress}" -gt "${end_index}" ]; then
		break
	fi

	echo "##### Image ${progress}/${end_index} - ${image}"
	container_name="$(basename "${image}" | sed -E 's/:/-/g')"
	# Ensure distrobox create works:
	"$(dirname "${0}")"/../distrobox create --yes -i "${image}" --name "${container_name}"
	# Ensure distrobox enter and init works:
	"$(dirname "${0}")"/../distrobox enter --name "${container_name}" -- whoami
	# Ensure distrobox list works:
	"$(dirname "${0}")"/../distrobox list | grep "${container_name}" | grep "${image}" | grep Up
	# Ensure distrobox stop works:
	"$(dirname "${0}")"/../distrobox stop --yes "${container_name}"
	# Ensure distrobox rm works:
	"$(dirname "${0}")"/../distrobox rm --force --name "${container_name}"

	# increase counter
	progress=$((progress + 1))
done
