#include "string.h"
#include "stdio.h"
#include "unistd.h"
#include "dlfcn.h"
#include "libgen.h"
#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif

#if defined(__APPLE__) && defined(__MACH__)
#include "TargetConditionals.h"
#if TARGET_OS_IPHONE
// iOS
#include "SDL3/SDL_main.h"
#else
// macOS
#endif
#else
// Other platforms
#endif

#define MAX_PATH 4096

static char szLauncherPath[MAX_PATH];
static char szEnginePath[MAX_PATH];
static char szTier0Path[MAX_PATH];

void *pEngineLib = NULL;
void *pTier0Lib = NULL;
typedef void (*EngineMainFn)(int argc, char** argv);
EngineMainFn pEngineMain;

extern "C" void FunnyMain( int argc, char **argv );

int main( int argc, char **argv ) {
#ifndef STATIC_BUILD
#ifdef __linux__
	readlink("/proc/self/exe",szLauncherPath, MAX_PATH);
	dirname(szLauncherPath);

	snprintf(szEnginePath, MAX_PATH, "%s/libengine.so", szLauncherPath);
	snprintf(szTier0Path, MAX_PATH, "%s/libtier0.so", szLauncherPath);
#endif
#ifdef __APPLE__
	uint32_t pathSize = sizeof(szLauncherPath);
	int pathResult = _NSGetExecutablePath(szLauncherPath, &pathSize);
	printf("%s\n",szLauncherPath);
	char *szLauncherPath2 = dirname(szLauncherPath);
	printf("%s\n",szLauncherPath2);
	snprintf(szEnginePath, MAX_PATH, "%s/libengine.dylib", szLauncherPath2);
	snprintf(szTier0Path, MAX_PATH, "%s/libtier0.dylib", szLauncherPath2);
#endif
	pTier0Lib = dlopen(szTier0Path, RTLD_NOW | RTLD_GLOBAL);
	if ( !pTier0Lib ) {
		printf("Failed to open libtier0\n");
		printf("\t%s\n",dlerror());
	}
	pEngineLib = dlopen(szEnginePath, RTLD_NOW | RTLD_GLOBAL);
	if ( !pEngineLib ) {
		printf("Failed to open libengine\n");
		printf("\t%s\n",dlerror());
	}
	pEngineMain = (EngineMainFn)dlsym(pEngineLib, "FunnyMain");
	if ( !pEngineMain ) {
		printf("Symbol not found: FunnyMain\n");
	}

	// chdir to right directory
	dirname(szLauncherPath);
	chdir(szLauncherPath);

	pEngineMain(argc, argv);
	dlclose(pEngineLib);
#else
	FunnyMain(argc, argv);
#endif
};
