# Check the presence of the current game script requirements
# USAGE: requirements_check
# RETURN: 0 if all required dependencies are available,
#         1 if a dependency is missing
requirements_check() {
	# Trigger an error if fetching the requirements list failed
	# `return 1` is not enough when called through test, so `exit 1` is used instead
	local requirements_list
	if ! requirements_list=$(requirements_list); then
		exit 1
	fi

	local requirement
	for requirement in $requirements_list; do
		if ! command -v "$requirement" >/dev/null 2>&1; then
			error_dependency_not_found "$requirement"
			return 1
		fi
	done

	# Debian - Check the available version of dpkg-deb
	local option_package
	option_package=$(option_value 'package')
	case "$option_package" in
		('deb')
			## Explicitly return an error status if the version check failed.
			if ! requirements_check_dpkg_deb_version; then
				return 1
			fi
		;;
	esac
}

# Check the available version of dpkg-deb
# USAGE: requirements_check_dpkg_deb_version
# RETURN: 0 if dpkg-deb is recent enough,
#         1 if dpkg-deb is too old.
requirements_check_dpkg_deb_version() {
	local version_available version_required
	version_available=$(
		LC_ALL=C dpkg-deb --version |
			sed --silent "s/Debian 'dpkg-deb' package archive backend version \\([\\.0-9]\\+\\) (amd64)\\./\\1/p"
	)
	## Throw an explicit error if current dpkg-deb version could not be fetched.
	if [ -z "$version_available" ]; then
		error_dpkg_version_not_found
		return 1
	fi
	## The required option --root-owner-group is only available with dpkg-deb ≥ 1.19.0.
	version_required='1.19.0'

	## If dpkg-deb is available, we can assume dpkg is available too.
	if ! dpkg --compare-versions "$version_available" '>=' "$version_required"; then
		error_requirement_too_old 'dpkg-deb' "$version_available" "$version_required"
		return 1
	fi
}

# Check the presence of the required commands for icons extraction
# USAGE: requirements_check_icons
requirements_check_icons() {
	# Return early if icons inclusion has been disabled.
	local option_icons
	option_icons=$(option_value 'icons')
	if [ "$option_icons" -eq 0 ]; then
		return 0
	fi

	local icons_requirements requirement
	icons_requirements=$(requirements_list_icons)
	for requirement in $icons_requirements; do
		if ! command -v "$requirement" >/dev/null 2>&1; then
			error_dependency_not_found "$requirement"
			return 1
		fi
	done
}

# output what a command is provided by
# USAGE: dependency_provided_by $command
# CALLED BY: error_dependency_not_found
dependency_provided_by() {
	local command provider
	command="$1"
	case "$command" in
		('7zr')
			provider='p7zip'
		;;
		('bsdtar')
			provider='libarchive'
		;;
		('convert'|'identify')
			provider='imagemagick'
		;;
		('lha')
			provider='lhasa'
		;;
		('icotool'|'wrestool')
			provider='icoutils'
		;;
		('dpkg-deb')
			provider='dpkg'
		;;
		(*)
			provider="$command"
		;;
	esac
	printf '%s' "$provider"
	return 0
}

