/*
  Copyright (c) 2013 Alex Diener
  
  This software is provided 'as-is', without any express or implied
  warranty. In no event will the authors be held liable for any damages
  arising from the use of this software.
  
  Permission is granted to anyone to use this software for any purpose,
  including commercial applications, and to alter it and redistribute it
  freely, subject to the following restrictions:
  
  1. The origin of this software must not be misrepresented; you must not
     claim that you wrote the original software. If you use this software
     in a product, an acknowledgment in the product documentation would be
     appreciated but is not required.
  2. Altered source versions must be plainly marked as such, and must not be
     misrepresented as being the original software.
  3. This notice may not be removed or altered from any source distribution.
  
  Alex Diener adiener@sacredsoftware.net
*/

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

#if defined(WIN32)
#include <windows.h>
#else
#include <dlfcn.h>
#endif

#include "unittest/framework/TestSuite.h"

TestSuite ** getTestSuites() {
	static char * testFileNames[] = {SUITE_FILE_LIST};
	static TestSuite * testSuites[sizeof(testFileNames) / sizeof(char *)];
	char suiteFunctionName[256];
	unsigned int suiteCount;
	unsigned int suiteIndex;
	struct TestSuite * (* suiteFunction)();
#if defined(WIN32)
	HMODULE moduleHandle;
	
	moduleHandle = GetModuleHandle(NULL);
#endif
	
	suiteCount = sizeof(testFileNames) / sizeof(char *) - 1;
	for (suiteIndex = 0; suiteIndex < suiteCount; suiteIndex++) {
		snprintf(suiteFunctionName, 256, "%s_suite", testFileNames[suiteIndex]);
#if defined(WIN32)
		suiteFunction = (struct TestSuite * (*)()) GetProcAddress(moduleHandle, suiteFunctionName);
#else
		suiteFunction = (struct TestSuite * (*)()) dlsym(RTLD_DEFAULT, suiteFunctionName);
#endif
		if (suiteFunction == NULL) {
			fprintf(stderr, "Couldn't load test suite %s (no symbol named %s found)\n", testFileNames[suiteIndex], suiteFunctionName);
			abort();
		}
		testSuites[suiteIndex] = suiteFunction();
	}
	testSuites[suiteIndex] = NULL;
	
	return testSuites;
}
