#!/bin/sh
# SPDX-License-Identifier: ACSL
# SPDX-FileCopyrightText: © 2018 Mopi
# SPDX-FileCopyrightText: © 2022 Antoine Le Gonidec <vv221@dotslashplay.it>
set -o errexit

###
# Spellforce
# send your bug reports to bugs@dotslashplay.it
###

script_version=20250312.1

PLAYIT_COMPATIBILITY_LEVEL='2.33'

GAME_ID='spellforce'
GAME_NAME='Spellforce'

ARCHIVE_BASE_0_NAME='setup_spellforce_-_platinum_edition_1.54.75000_(17748).exe'
ARCHIVE_BASE_0_MD5='ed34fb43d8042ff61a889865148b8dd2'
ARCHIVE_BASE_0_TYPE='innosetup'
ARCHIVE_BASE_0_PART1_NAME='setup_spellforce_-_platinum_edition_1.54.75000_(17748)-1.bin'
ARCHIVE_BASE_0_PART1_MD5='60fca014e7ccd4630a7ec3cedb23942a'
ARCHIVE_BASE_0_SIZE='3900000'
ARCHIVE_BASE_0_VERSION='1.54.7500-gog17748'
ARCHIVE_BASE_0_URL='https://www.gog.com/game/spellforce_platinum'

CONTENT_PATH_DEFAULT='app'
CONTENT_GAME_BIN_FILES='
binkw32.dll
dbghelp.dll
mss32.dll
ar.exe
spellforce.exe'
## This file, generated below, includes the required CD-key.
CONTENT_GAME0_BIN_FILES='
cdkey'
CONTENT_GAME_DATA_FILES='
data
map
miles
pak
videos
spellforce_addon.ico
spellforce_addon2.ico'
CONTENT_DOC_DATA_FILES='
manual.pdf
readme.rtf'

WINE_PERSISTENT_DIRECTORIES='
users/${USER}/Documents/SpellForce'

USER_PERSISTENT_FILES='
config.lua'

APP_MAIN_EXE='spellforce.exe'

PACKAGES_LIST='
PKG_BIN
PKG_DATA'

PKG_BIN_ARCH='32'
PKG_BIN_DEPENDENCIES_SIBLINGS='
PKG_DATA'

PKG_DATA_ID="${GAME_ID}-data"
PKG_DATA_DESCRIPTION='data'

# Load common functions

PLAYIT_LIB_PATHS="
$PWD
${XDG_DATA_HOME:="${HOME}/.local/share"}/play.it
/usr/local/share/games/play.it
/usr/local/share/play.it
/usr/share/games/play.it
/usr/share/play.it"

if [ -z "$PLAYIT_LIB2" ]; then
	for playit_lib_path in $PLAYIT_LIB_PATHS; do
		if [ -e "${playit_lib_path}/libplayit2.sh" ]; then
			PLAYIT_LIB2="${playit_lib_path}/libplayit2.sh"
			break
		fi
	done
fi
if [ -z "$PLAYIT_LIB2" ]; then
	printf '\n\033[1;31mError:\033[0m\n'
	printf 'libplayit2.sh not found.\n'
	exit 1
fi
# shellcheck source=libplayit2.sh
. "$PLAYIT_LIB2"

# Run the default initialization actions

initialization_default "$@"

# Extract game data

archive_extraction_default
(
	cd "${PLAYIT_WORKDIR}/gamedata/$(content_path_default)"

	# Fetch the required CD-key from the installer script
	sed --silent '125s/.*"valueData": "\(.*\)",/\1/p' goggame-1207658719.script > 'cdkey'
)

# Include game data

content_inclusion_icons 'PKG_DATA'
content_inclusion_default

# Write launchers

## Register the game CD-key
wineprefix_init_custom() {
	cat <<- 'EOF'
	# Register the game CD-key
	cdkey=$(cat "${PATH_GAME_DATA}/cdkey")
	$(wine_command) reg add "HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\SpellForce" /v "CDKEY" /t REG_SZ /d "$cdkey" /f
	EOF
}

launchers_generation 'PKG_BIN'

# Build packages

packages_generation
print_instructions

# Clean up

working_directory_cleanup

exit 0
