#!/bin/sh
set -o nounset

oneTimeSetUp() {
	# Load the ./play.it library.
	. lib/libplayit2.sh
}

setUp() {
	# Set a temporary directory to mess with real files
	TEST_TEMP_DIR=$(mktemp --directory)
	export TEST_TEMP_DIR
}

tearDown() {
	rm --force --recursive "$TEST_TEMP_DIR"
}

# Check that setting a dependency on an unkown Mono library is allowed.
test_unknown_mono_library() {
	## Prevent actions requiring the creation/modification of files.
	dependencies_unknown_mono_libraries_add() { return 0; }

	assertTrue \
		'dependencies_mono_single_debian choked on an unkwown Mono library.' \
		'dependencies_mono_single_debian "Mono.unknown.dll"'

	unset -f dependencies_unknown_mono_libraries_add

	return 0
}

# Check that the correct Unity3D game binary is picked up.
test_unity3d_binary_identification() {
	local \
		CONTENT_PATH_DEFAULT='.' \
		PLAYIT_WORKDIR="$TEST_TEMP_DIR" \
		UNITY3D_NAME='Dungeons2'

	## package_path rely on the target package format being set,
	## this is not what we are trying to test here.
	package_path() {
		printf '/nonexistent'
	}

	mkdir --parents "${PLAYIT_WORKDIR}/gamedata/${CONTENT_PATH_DEFAULT}"
	touch \
		"${PLAYIT_WORKDIR}/gamedata/${CONTENT_PATH_DEFAULT}/${UNITY3D_NAME}" \
		"${PLAYIT_WORKDIR}/gamedata/${CONTENT_PATH_DEFAULT}/${UNITY3D_NAME}.x86"
	assertEquals \
		'unity3d_application_exe_default picked up the wrong file as the main game binary.' \
		"${UNITY3D_NAME}.x86" \
		"$(unity3d_application_exe_default 'APP_MAIN')"

	unset -f package_path

	return 0
}

# Check that packages_generation called without an explicit list of packages does no end up running twice.
test_packages_generation_extra_call() {
	local \
		PLAYIT_OPTION_PACKAGE='deb' \
		function_calls_counter=0

	debian_packages_metadata() {
		function_calls_counter=$((function_calls_counter + 1))
		export function_calls_counter
	}
	debian_packages_build() { return 0; }

	## Prevent the console message from being mixed with shunit2 output.
	packages_generation >/dev/null
	assertEquals \
		'packages_generation called without an argument ended up running multiple times instead of only once.' \
		'1' "$function_calls_counter"

	unset -f debian_packages_metadata debian_packages_build

	return 0
}

# Ensure that an error is thrown when trying to extract icons from an application with no icon set.
test_icon_extraction_witout_icon() {
	local \
		ARCHIVE_OPTIONAL_ICONS_NAME

	## Prevent actions requiring files manipulation.
	icons_inclusion_single_icon() { return 0; }

	assertFalse \
		'icons_inclusion_single_application failed to notice it has been asked to handle an application with no icon set.' \
		'icons_inclusion_single_application "PKG_MAIN" "APP_MAIN"'

	ARCHIVE_OPTIONAL_ICONS_NAME='alpha-centauri-icons.2022-10-04.tar.gz'
	assertTrue \
		'icons_inclusion_single_application failed to notice that an optional icons archive is supported.' \
		'icons_inclusion_single_application "PKG_MAIN" "APP_MAIN"'

	unset -f icons_inclusion_single_icon

	return 0
}
