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

###
# Alpha Centauri
# send your bug reports to vv221@dotslashplay.it
###

script_version=20260311.4

PLAYIT_COMPATIBILITY_LEVEL='2.35'

GAME_ID='alpha-centauri'
GAME_NAME='Alpha Centauri'

ARCHIVE_BASE_1_NAME='setup_sid_meiers_alpha_centauri_planetary_pack_1.1_pracx_ddraw_(77244).exe'
ARCHIVE_BASE_1_MD5='d401431ff9c1c7526c3104194409bd6e'
ARCHIVE_BASE_1_EXTRACTOR='innoextract'
ARCHIVE_BASE_1_EXTRACTOR_OPTIONS='--lowercase'
ARCHIVE_BASE_1_VERSION='6.0b-gog77244'
ARCHIVE_BASE_1_SIZE='601205'
ARCHIVE_BASE_1_URL='https://www.gog.com/game/sid_meiers_alpha_centauri'

ARCHIVE_BASE_0_NAME='setup_sid_meiers_alpha_centauri_2.0.2.23.exe'
ARCHIVE_BASE_0_MD5='6c9bd7e1cf88fdbfa0e75f694bf8b0e5'
ARCHIVE_BASE_0_EXTRACTOR='innoextract'
ARCHIVE_BASE_0_EXTRACTOR_OPTIONS='--lowercase'
ARCHIVE_BASE_0_VERSION='6.0b-gog2.0.2.23'
ARCHIVE_BASE_0_SIZE='609309'

# Loki native Linux engine
ARCHIVE_REQUIRED_ENGINE_NAME='alpha-centauri-linux.tar.xz'
ARCHIVE_REQUIRED_ENGINE_MD5='a13676f2bdf1d3570ebb1835c2e4b2e8'
ARCHIVE_REQUIRED_ENGINE_URL='https://downloads.dotslashplay.it/games/alpha-centauri/'

# Optional icons pack
ARCHIVE_OPTIONAL_ICONS_NAME='alpha-centauri-icons.2022-10-04.tar.gz'
ARCHIVE_OPTIONAL_ICONS_MD5='9293b41c5b0ab978ff007f78d29fbbcf'
ARCHIVE_OPTIONAL_ICONS_URL='https://downloads.dotslashplay.it/games/alpha-centauri/'
CONTENT_ICONS_PATH='.'
CONTENT_ICONS_FILES='
16x16
32x32
48x48'

CONTENT_PATH_DEFAULT='.'
CONTENT_PATH_DEFAULT_0='app'
CONTENT_GAME_BIN_PATH='.'
CONTENT_GAME_BIN_FILES='
smac
smac.dynamic
smacx
smacx.dynamic
smacpack'
CONTENT_GAME_MOVIES_FILES='
data/movies'
CONTENT_FONTS_DATA_FILES='
alphc___.ttf
arialnbi.ttf
arialnb.ttf
arialni.ttf
arialn.ttf'
CONTENT_FONTS0_DATA_PATH='data/fonts'
CONTENT_FONTS0_DATA_FILES='
arialb.ttf
ariali.ttf
arialr.ttf
loki_times.ttf'
CONTENT_GAME_DATA_FILES='
data/facs
data/fx
data/maps
data/projs
data/scenarios
data/techs
data/voices
data/alieniscript.txt
data/alienuscript.txt
data/alpha.txt
data/alphax.txt
data/angels.txt
data/basename.txt
data/believe.txt
data/blurbs.txt
data/blurbsx.txt
data/brian.txt
data/caretake.txt
data/concepts.txt
data/conceptsx.txt
data/credits.txt
data/cyborg.txt
data/drone.txt
data/facedit.txt
data/faction.txt
data/flavor.txt
data/fungboy.txt
data/gaians.txt
data/help.txt
data/helpx.txt
data/hive.txt
data/holobook.txt
data/humanludes.txt
data/interludea.txt
data/interlude.txt
data/interludex.txt
data/jackal.txt
data/labels.txt
data/logfile.txt
data/menu.txt
data/monument.txt
data/morgan.txt
data/movlist.txt
data/peace.txt
data/pirates.txt
data/planets.txt
data/scenario.txt
data/script.txt
data/sid.txt
data/spartans.txt
data/system.txt
data/techlongs.txt
data/techshorts.txt
data/tutor.txt
data/univ.txt
data/usurper.txt
data/xscript.txt
data/*.cfg
data/*.cvr
data/*.flc
data/*.pcx
data/*.sys'
CONTENT_GAME0_DATA_PATH='.'
CONTENT_GAME0_DATA_FILES='
data'
CONTENT_DOC_DATA_FILES='
manual.pdf'
CONTENT_DOC0_DATA_RELATIVE_PATH='data'
CONTENT_DOC0_DATA_FILES='
readme.txt
readme_ac.txt
smac_xp2000_readme.txt'

APP_MAIN_EXE='smac.dynamic'
APP_MAIN_ICON='terran.exe'
# Work around font rendering problems.
# cf. https://freetype.org/freetype2/docs/reference/ft2-properties.html#tt_interpreter_version_xxx
# (FreeType 2.14.2)
APP_MAIN_PRERUN='
# Work around font rendering problems.
# cf. https://freetype.org/freetype2/docs/reference/ft2-properties.html#tt_interpreter_version_xxx
# (FreeType 2.14.2)
export FREETYPE_PROPERTIES="truetype:interpreter-version=35"
'
# Work around a rendering failure.
# cf. https://github.com/libsdl-org/sdl2-compat/issues/581
# (SDL 3.4.2)
APP_MAIN_PRERUN="${APP_MAIN_PRERUN:-}
# Work around a rendering failure.
# cf. https://github.com/libsdl-org/sdl2-compat/issues/581
# (SDL 3.4.2)
export SDL_RENDER_DRIVER=vulkan
"

APP_SMACX_ID="${GAME_ID}-alien-crossfire"
APP_SMACX_NAME="$GAME_NAME - Alien Crossfire"
APP_SMACX_EXE='smacx.dynamic'
APP_SMACX_ICON='terranx.exe'
APP_SMACX_PRERUN="$APP_MAIN_PRERUN"

PACKAGES_LIST='
PKG_BIN
PKG_MOVIES
PKG_DATA'

PKG_BIN_ARCH='32'
PKG_BIN_DEPENDENCIES_SIBLINGS='
PKG_MOVIES
PKG_DATA'
PKG_BIN_DEPENDENCIES_LIBRARIES='
libc.so.6
libEGL.so.1
libfreetype.so.6
libm.so.6
libpthread.so.0
libSDL-1.2.so.0
libSDL_mixer-1.2.so.0
libSDL_ttf-2.0.so.0
libsmpeg-0.4.so.0
libz.so.1'

PKG_MOVIES_ID="${GAME_ID}-movies"
PKG_MOVIES_DESCRIPTION='movies'

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

# LD_PRELOAD shim allowing the old engine to run on top of current SDL libraries.
# cf. https://github.com/ZeroPointEnergy/lokishim
LD_PRELOAD_SOURCE='
#define _GNU_SOURCE

#include <stdio.h>
#include <stdlib.h>

void *__builtin_new(size_t size) {
	return malloc(size);
}

void __builtin_delete(void *ptr) {
	free(ptr);
}

void *__builtin_vec_new(size_t size) {
	return malloc(size);
}

void __builtin_vec_delete(void *ptr) {
	free(ptr);
}
'

# Convert text files to UNIX-style line breaks.
REQUIREMENTS_LIST="${REQUIREMENTS_LIST:-}
dos2unix"

# Convert movies from the original format.
REQUIREMENTS_LIST="${REQUIREMENTS_LIST:-}
ffmpeg
mplex"

# Load common functions.

if [ -z "$PLAYIT_LIB2" ]; then
	for playit_lib_dir in \
		"$PWD" \
		"${HOME}/.local/lib/play.it" \
		'/usr/local/lib/play.it' \
		'/usr/lib/play.it'
	do
		playit_lib_path="${playit_lib_dir}/libplayit.sh.2"
		if [ -e "$playit_lib_path" ]; then
			PLAYIT_LIB2="$playit_lib_path"
			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 default initialisation actions.

initialization_default "$@"

# Check for the native engine availability.

archive_initialize_required \
	'ARCHIVE_ENGINE' \
	'ARCHIVE_REQUIRED_ENGINE'

# Check that the "rename" command is available.

unset RENAME_CMD
# On Arch Linux it is provided under the name "perl-rename".
for rename_cmd in 'perl-rename' 'rename'; do
	if command -v "$rename_cmd" >/dev/null 2>&1; then
		RENAME_CMD="$rename_cmd"
		break
	fi
done
if [ -z "${RENAME_CMD:-}" ]; then
	error_dependency_not_found 'rename'
	exit 1
fi

# Extract game data.

archive_extraction_default
archive_extraction 'ARCHIVE_ENGINE'
# Drop unused alternative art assets.
path_archive_contents=$(path_archive_contents)
rm --force --recursive \
	"${path_archive_contents}/alternative art" \
	"${path_archive_contents}/color blind palette"
# Replace spaces in file paths by underscores.
find "${path_archive_contents}" -depth -name '* *' -execdir \
	"$RENAME_CMD" 's/ /_/g' {} +
# Convert text files to UNIX-style line breaks.
find "${path_archive_contents}" -type f -name '*.txt' -exec \
	dos2unix --quiet {} +
# Move data files into the expected paths.
mkdir --parents "${path_archive_contents}/data"
mv --target-directory="${path_archive_contents}/data" -- \
	"${path_archive_contents}"/facs \
	"${path_archive_contents}"/fx \
	"${path_archive_contents}"/maps \
	"${path_archive_contents}"/projs \
	"${path_archive_contents}"/techs \
	"${path_archive_contents}"/voices \
	"${path_archive_contents}"/*.cvr \
	"${path_archive_contents}"/*.flc \
	"${path_archive_contents}"/*.pcx \
	"${path_archive_contents}"/*.sys \
	"${path_archive_contents}"/*.txt
mv \
	"${path_archive_contents}/scenarios/alpha_centauri_scenarios" \
	"${path_archive_contents}/data/scenarios"
if [ -e "${path_archive_contents}/__support/app/ip.cfg" ]; then
	mv \
		"${path_archive_contents}/__support/app/ip.cfg" \
		"${path_archive_contents}/data/ip.cfg"
else
	mv \
		"${path_archive_contents}/ip.cfg" \
		"${path_archive_contents}/data/ip.cfg"
fi

# Convert movies from the original format.

case "$(messages_language)" in
	('fr')
		message_begin='Conversion des fichiers vidéo, cette étape peut prendre plusieurs minutes…\n'
		message_done='Conversion terminée\n'
	;;
	('en'|*)
		message_begin='Converting video files, this will take several minutes…\n'
		message_done='Converting done\n'
	;;
esac
printf "$message_begin"
destination_directory="${path_archive_contents}/data/movies"
mkdir "$destination_directory"
find "${path_archive_contents}/movies" -name '*.wve' -print0 |
	xargs --null --max-args=1 --max-procs="$(nproc)" sh -c '
	destination_directory=$1
	source_file=$2
	stream_video="${source_file%.wve}.m1v"
	stream_audio="${source_file%.wve}.mp2"
	destination_file="${destination_directory}/$(basename "$source_file" .wve).mpg"
	ffmpeg -i "$source_file" -loglevel quiet -map v -codec:v mpeg1video -b:v 1727k -minrate 1727k -maxrate 1727k -r 29.97 "$stream_video"
	ffmpeg -i "$source_file" -loglevel quiet -map a -codec:a mp2 -ar 44100 "$stream_audio"
	rm "$source_file"
	mplex --verbose 0 --video-buffer 500 --output "$destination_file" "$stream_video" "$stream_audio"
	rm "$stream_video" "$stream_audio"
	' -- "$destination_directory"
printf "$message_done"

# Include game data.

content_inclusion_icons 'PKG_DATA'
content_inclusion_default

# Link the fonts in the hardcoded path the game engine expects.

fonts_source=$(path_fonts_ttf)
fonts_destination="$(package_path 'PKG_DATA')$(path_game_data)/data/fonts"
mkdir --parents "$fonts_destination"
for font_file in \
	'alphc___.ttf' \
	'arialr.ttf' \
	'arialb.ttf' \
	'ariali.ttf' \
	'arialn.ttf' \
	'arialnb.ttf' \
	'arialni.ttf' \
	'arialnbi.ttf' \
	'loki_times.ttf'
do
	ln --symbolic "${fonts_source}/${font_file}" "$fonts_destination"
done

# Write launchers.

launchers_generation

# Build packages.

packages_generation
print_instructions

# Clean up.

working_directory_cleanup

exit 0
