# Get the compatibility level that has been requested
# USAGE: compatibility_level
# RETURN: the requested compatibility level,
#         defaulting to the current library version
compatibility_level() {
	local compatibility_level

	if [ -n "${PLAYIT_COMPATIBILITY_LEVEL:-}" ]; then
		compatibility_level="$PLAYIT_COMPATIBILITY_LEVEL"
	else
		## The bugfix version number is trimmed, to get a value respecting the expected "major.minor" format.
		compatibility_level="${PLAYIT_LIBRARY_VERSION%.*}"
	fi

	# Check the validity of the compatibility level format
	local regexp
	regexp='^[1-9][0-9]*\.[0-9]\+$'
	if ! printf '%s' "$compatibility_level" | grep --quiet --regexp="$regexp"; then
		error_invalid_compatibility_level "$compatibility_level"
		return 1
	fi

	printf '%s' "$compatibility_level"
}

# Check the compatibility level against a given version
# USAGE: compatibility_level_is_at_least $minimum_version
# RETURN: 0 if the compatibility level is equal or superior to the given level,
#         1 if the compatibility level is inferior to the given level
compatibility_level_is_at_least() {
	local minimum_version compatibility_level
	minimum_version="$1"
	if ! compatibility_level=$(compatibility_level); then
		## Stop the script execution if the compatibility level is not set to a valid value.
		## This needs to be done explicitly because this functions is called from tests.
		exit 1
	fi

	# Compare major version fields
	local minimum_version_major compatibility_level_major
	minimum_version_major=$(printf '%s' "$minimum_version" | cut --delimiter='.' --fields=1)
	compatibility_level_major=$(printf '%s' "$compatibility_level" | cut --delimiter='.' --fields=1)
	if [ "$compatibility_level_major" -lt "$minimum_version_major" ]; then
		return 1
	elif [ "$compatibility_level_major" -gt "$minimum_version_major" ]; then
		return 0
	else
		# Compare minor version fields
		local minimum_version_minor compatibility_level_minor
		minimum_version_minor=$(printf '%s' "$minimum_version" | cut --delimiter='.' --fields=2)
		compatibility_level_minor=$(printf '%s' "$compatibility_level" | cut --delimiter='.' --fields=2)
		if [ "$compatibility_level_minor" -lt "$minimum_version_minor" ]; then
			return 1
		elif [ "$compatibility_level_minor" -ge "$minimum_version_minor" ]; then
			return 0
		fi
	fi
}

