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

###
# Anomaly Defenders
# send your bug reports to bugs@dotslashplay.it
###

script_version=20250823.1

PLAYIT_COMPATIBILITY_LEVEL='2.33'

GAME_ID='anomaly-defenders'
GAME_NAME='Anomaly Defenders'

ARCHIVE_BASE_LINUX_ZIP_0_NAME='AnomalyDefenders_Linux_1402514865.zip'
ARCHIVE_BASE_LINUX_ZIP_0_MD5='430367c8228077e4c8af2f5e7f164f4e'
ARCHIVE_BASE_LINUX_ZIP_0_SIZE='640000'
ARCHIVE_BASE_LINUX_ZIP_0_VERSION='1.0-humble'
ARCHIVE_BASE_LINUX_ZIP_0_URL='https://www.humblebundle.com/store/anomaly-defenders'

ARCHIVE_BASE_LINUX_TARGZ_0_NAME='AnomalyDefenders_Linux_1402512837.tar.gz'
ARCHIVE_BASE_LINUX_TARGZ_0_MD5='35ccd57e8650dd53a09b1f1e088307cc'
ARCHIVE_BASE_LINUX_TARGZ_0_SIZE='640000'
ARCHIVE_BASE_LINUX_TARGZ_0_VERSION='1.0-humble'
ARCHIVE_BASE_LINUX_TARGZ_0_URL='https://www.humblebundle.com/store/anomaly-defenders'

ARCHIVE_BASE_WINDOWS_0_NAME='AnomalyDefenders_Windows_Setup_1402514865.exe'
ARCHIVE_BASE_WINDOWS_0_MD5='23ebfeaf0c8b9fda0d5ce73f3a33bdae'
ARCHIVE_BASE_WINDOWS_0_TYPE='innosetup'
ARCHIVE_BASE_WINDOWS_0_SIZE='645916'
ARCHIVE_BASE_WINDOWS_0_VERSION='1.0-humble'
ARCHIVE_BASE_WINDOWS_0_URL='https://www.humblebundle.com/store/anomaly-defenders'

CONTENT_PATH_DEFAULT_LINUX='AnomalyDefenders'
CONTENT_PATH_DEFAULT_WINDOWS='app'
CONTENT_LIBS_BIN_FILES_LINUX='
libOpenAL.so'
CONTENT_GAME_BIN_FILES_LINUX='
AnomalyDefenders'
CONTENT_GAME_BIN_FILES_WINDOWS='
libcurl.dll
pctouchhelper.dll
anomalydefenders.exe'
## icon.png is only provided by the Linux build.
CONTENT_GAME_DATA_FILES='
icon.png
*.dat
*.idx'
## These documentation files are only provided by the Linux build.
CONTENT_DOC_DATA_FILES='
README
Copyright license*'

## LD_PRELOAD shim working around infinite loading times
LD_PRELOAD_SOURCE_LINUX='
#define _GNU_SOURCE
#include <dlfcn.h>
#include <semaphore.h>
#include <stdio.h>
#include <time.h>
#include <unistd.h>

static int (*_realSemTimedWait)(sem_t *, const struct timespec *) = NULL;

int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout) {
	if (abs_timeout->tv_nsec >= 1000000000) {
		((struct timespec *)abs_timeout)->tv_nsec -= 1000000000;
		((struct timespec *)abs_timeout)->tv_sec++;
	}
	return _realSemTimedWait(sem, abs_timeout);
}
__attribute__((constructor)) void init(void) {
	_realSemTimedWait = dlsym(RTLD_NEXT, "sem_timedwait");
}
'

WINE_PERSISTENT_DIRECTORIES='
users/${USER}/AppData/Roaming/11bitstudios/Anomaly Defenders'

## The Linux build triggers a segmentation fault on Mesa ≥ 23.0.0 right after the introduction video:
##
## #0  0x0829e6d8 in NameStringManager::ReleaseString(char const*) [clone .constprop.21] ()
## #1  0x08193d73 in SoundEntriesContainer::~SoundEntriesContainer() ()
## #2  0xf77a78da in __run_exit_handlers (status=<optimized out>, listp=<optimized out>, run_list_atexit=<optimized out>, run_dtors=<optimized out>) at ./stdlib/exit.c:118
## #3  0xf77a7af1 in __GI_exit (status=1) at ./stdlib/exit.c:148
## #4  0xf7db7930 in _XDefaultError (event=0xe3eff04c, dpy=0x855fe00) at ../../src/XlibInt.c:1440
## #5  _XDefaultError (dpy=0x855fe00, event=0xe3eff04c) at ../../src/XlibInt.c:1425
## #6  0xf7db7a58 in _XError (dpy=0x855fe00, rep=0xe3eff0fc) at ../../src/XlibInt.c:1494
## #7  0xf753243f in __glXSendError (dpy=0x855fe00, errorCode=10 '\n', resourceID=0, minorCode=5, coreX11error=true) at ../src/glx/glx_error.c:62
## #8  0xf7532294 in MakeContextCurrent (dpy=<optimized out>, draw=10485767, read=10485767, gc_user=<optimized out>, opcode=<optimized out>) at ../src/glx/glxcurrent.c:147
## #9  0xf76b38c6 in InternalMakeCurrentVendor (dpy=dpy@entry=0x855fe00, draw=draw@entry=10485767, read=read@entry=10485767, ctxInfo=0xe3fb03c0, callerOpcode=5 '\005', threadState=<optimized out>, vendor=0x84ef030) at ../src/GLX/libglx.c:871
## #10 0xf76b4210 in InternalMakeCurrentDispatch (dpy=dpy@entry=0x855fe00, draw=draw@entry=10485767, read=read@entry=10485767, ctxInfo=0xe3fb03c0, callerOpcode=5 '\005', vendor=0x84ef030) at ../src/GLX/libglx.c:926
## #11 0xf76b5434 in CommonMakeCurrent (dpy=0x855fe00, draw=10485767, read=10485767, context=0xe3f00720, callerOpcode=5 '\005') at ../src/GLX/libglx.c:1070
## #12 0x0805c1c5 in LinuxStandaloneGame::_SetGLContext(LinuxStandaloneGame::LxThread) ()
## #13 0x0805d257 in SetGLContextPresenterThread() ()
## #14 0x080e5a87 in LiquidRendererPresenterThread::_OnProcessMessage(MessageHeader*) ()
## #15 0x082a91f4 in BaseThread::_ProcessMessageQueue() ()
## #16 0x082a8bcc in BaseThread::ThreadCodeDispatch(void*) ()
## #17 0xf77f9781 in start_thread (arg=<optimized out>) at ./nptl/pthread_create.c:448
## #18 0xf788fe38 in __GI___clone3 () at ../sysdeps/unix/sysv/linux/i386/clone3.S:111
##
## This has been reported to Mesa developers, but they decided that they will not provide a fix:
## https://gitlab.freedesktop.org/mesa/mesa/-/issues/12246
## Their suggestion is to buy the game on Steam (!!) and play it through Proton (!!!).
##
## The following patch, not included in upstream Mesa, might prevent that crash:
## --- a/src/glx/glxcurrent.c
## +++ b/src/glx/glxcurrent.c
## @@ -138,6 +138,11 @@ MakeContextCurrent(Display * dpy, GLXDrawable draw,
##     __glXSetCurrentContextNull();
##
##     if (gc) {
## +      if (gc->currentDpy && gc->currentDpy == dpy) {
## +         gc->vtable->unbind(gc);
## +         gc->currentDpy = NULL;
## +      }
## +
##        /* GLX spec 3.3: If ctx is current to some other thread, then
##         * glXMakeContextCurrent will generate a BadAccess error
##         */
##
## Support for the Windows build is included as a workaround.
APP_MAIN_EXE_LINUX='AnomalyDefenders'
APP_MAIN_EXE_WINDOWS='anomalydefenders.exe'
APP_MAIN_ICON_LINUX='icon.png'

PACKAGES_LIST='
PKG_BIN
PKG_DATA'

PKG_BIN_ID="${GAME_ID}-bin"
PKG_BIN_ID_LINUX="${PKG_BIN_ID}-linux"
PKG_BIN_ID_WINDOWS="${PKG_BIN_ID}-windows"
PKG_BIN_PROVIDES="
$PKG_BIN_ID"
PKG_BIN_ARCH='32'
PKG_BIN_DEPENDENCIES_SIBLINGS='
PKG_DATA'
PKG_BIN_DEPENDENCIES_LIBRARIES_LINUX='
libc.so.6
libgcc_s.so.1
libGL.so.1
libm.so.6
libpthread.so.0
librt.so.1
libstdc++.so.6
libX11.so.6'
## Ensure easy upgrades from packages generated with pre-20250123.1 game scripts
PKG_BIN_PROVIDES="${PKG_BIN_PROVIDES:-}
anomaly-defenders"

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 default initialisation actions.

initialization_default "$@"

# Extract game data.

archive_extraction_default

# Include game data.

content_inclusion_icons 'PKG_DATA'
content_inclusion_default

# Write launchers.

launchers_generation

# Build packages.

packages_generation
print_instructions

# Clean up.

working_directory_cleanup

exit 0
