# Set the identifier of the current package
# USAGE: set_current_package $package
set_current_package() {
	local package
	package="$1"

	# Check that the identifier uses the expected PKG_xxx format.
	local regexp
	regexp='^PKG\(_[0-9A-Z]\+\)\+$'
	if ! printf '%s' "$package" | grep --quiet --regexp="$regexp"; then
		error_current_package_format_invalid "$package"
		## exit is used instead of return to ensure a failure when called from a subshell.
		exit 1
	fi

	# Check that the identifier is included in the list of packages to build.
	if ! package_is_included_in_packages_list "$package"; then
		error_current_package_not_in_list "$package"
		## exit is used instead of return to ensure a failure when called from a subshell.
		exit 1
	fi

	export PLAYIT_CONTEXT_PACKAGE="$package"
}

# Set the identifier of the default package
# USAGE: set_default_package $package
set_default_package() {
	local package
	package="$1"

	# Check that the identifier uses the expected PKG_xxx format.
	local regexp
	regexp='^PKG\(_[0-9A-Z]\+\)\+$'
	if ! printf '%s' "$package" | grep --quiet --regexp="$regexp"; then
		error_current_package_format_invalid "$package"
		return 1
	fi

	# Check that the identifier is included in the list of packages to build.
	if ! package_is_included_in_packages_list "$package"; then
		error_current_package_not_in_list "$package"
		return 1
	fi

	export PLAYIT_CONTEXT_PACKAGE_DEFAULT="$package"
}

# Print the identifier of the current package.
# USAGE: current_package
# RETURN: the current package identifier,
#         or an empty string if none is set
current_package() {
	# To ensure backwards-compatibility, the legacy variable should have a higher priority than the modern one.
	# Otherwise the ability to set the context using $PKG from game scripts would be lost as soon as the library calls set_current_package.
	local package
	package="${PKG:-}"
	if
		[ -n "$package" ] &&
		compatibility_level_is_at_least '2.27'
	then
		warning_context_legacy_package
	fi

	if [ -z "$package" ]; then
		package="${PLAYIT_CONTEXT_PACKAGE:-}"
	fi

	# If no package context is explicitly set, set it to the first package in the list of packages to build.
	if [ -z "$package" ]; then
		package=$(default_package)
	fi

	printf '%s' "$package"
}

# Print the identifier of the default package.
# USAGE: default_package
# RETURN: the default package identifier,
#         or an empty string if none is set
default_package() {
	printf '%s' "${PLAYIT_CONTEXT_PACKAGE_DEFAULT:-}"
}

