#!/bin/bash

# a few compiler invocations that should do about the same thing as the real build system.
#
# may be used
#   - for understanding what the 'big' buildsystem actually does
#   - as a last resort, if you can't get cmake to work
#   - if you ever wanted to do a single g++ invocation that takes serveral minutes to complete
#
# depending on your distribution and current decade, minor or major adjustments may be necessary.
#
# this script was written by carefully looking at the output of make VERBOSE=1.
# if you add libraries/etc to the project, please update this script accordingly (and test it).

PYVER=3.4m
PYVERDOTLESS=34m
shopt -s globstar

function run() {
	echo "$@"
	"$@" || exit
}

# these three files would be configured by cmake

echo "# generated by buildsystem/simple
GLOBAL_ASSET_DIR = '/usr/local/share/openage'
VERSION = '`cat openage_version`'
CONFIG_OPTIONS = ''
COMPILER = 'gcc'
COMPILERFLAGS = '-O2 -Wall -Wextra -pedantic -std=c++14'
CYTHONVERSION = '`python3 -m cython --version 2>&1`'
# EOF" > openage/config.py

echo " // generated by buildsystem/simple
#ifndef openage_config_h_
#define openage_config_h_
#define WITH_BACKTRACE false
#define WITH_INOTIFY false
#define WITH_GPERFTOOLS_PROFILER false
#define WITH_GPERFTOOLS_TCMALLOC false
namespace openage { namespace config {
extern const char *const global_asset_dir;
extern const char *const version;
extern const char *const config_option_string;
constexpr const char *buildsystem_sourcefile_dir = \"`pwd`\";
}}
#endif" > libopenage/config.h

echo "// generated by buildsystem/simple
#include \"config.h\"
namespace openage { namespace config {
const char *const global_asset_dir = \"/usr/local/share/openage\";
const char *const version = \"`cat openage_version`\";
const char *const config_option_string = \"< none >\";
}}" > libopenage/config.cpp

# codegen
run python3 -m openage codegen --generated-list-file=/tmp/codegen_gen --depend-list-file=/tmp/codegen_depends --mode=codegen

# build libopenage.so
run g++ -Wall -Wextra -pedantic -std=c++14 -O2 -fPIC -shared \
        -I/usr/include/freetype2 -I/usr/include/FTGL -I/usr/include/libpng16 -I/usr/include/harfbuzz -I/usr/include/opus -I/usr/include/SDL2 \
        -lfontconfig -lfreetype -lftgl -lepoxy -lm -lGLU -lGL -lSM -lICE -lX11 -lXext -lopusfile -lSDL2_image -lSDL2 -lpthread -lutil -lrt -ldl \
        -o libopenage.so libopenage/**/*.cpp

# pxdgen
run python3 -m buildsystem.pxdgen libopenage/**/*.h

# build py ext modules
for file in openage/**/*.pyx; do

run python3 -m cython --cplus -3 $file || exit
run g++ -Wall -Wextra -pedantic -std=c++14 -O2 -fPIC -shared -fwrapv -fstack-protector-strong -D_FORTIFY_SOURCE=2 -include libopenage/pyinterface/hacks.h \
        -I/usr/include/python${PYVER} \
        -pthread -Wl,-O2,-Bsymbolic-functions,-z,relro,-rpath,`pwd` -lopenage -L`pwd` \
        -o ${file%.pyx}.cpython-${PYVERDOTLESS}.so ${file%.pyx}.cpp

done
