#!/usr/bin/env python3

#totally braindead and stupid configure file for openage
#
#rewrite it if you got any better idea.
#
#
# packagers: you don't have to use this file.
# ---------  it exists for convenience so that users
#            don't have to know the cmake invocations.
#            -> build this project as a regular cmake project
#               the way you are used to it.


import os
import argparse

cmake_binary = "cmake"

aboutmsg = "openage configure script, initializes cmake so you can compile the project afterwards"
epilogmsg = "this script honors the CXX environment variable, but it has a lower priority than the --compiler option."

ap = argparse.ArgumentParser(description=aboutmsg, epilog=epilogmsg)
ap.add_argument("--mode", "-m", choices=["debug", "release"], default="release", help="an integer for the accumulator")
ap.add_argument("--compiler", "-c", help="the compiler to use: clang++, g++")


def prepare_binfolder():
	os.makedirs("bin", exist_ok=True)
	os.chdir("bin/")

def get_build_type(t):
	prefix = "-DCMAKE_BUILD_TYPE="
	res = ""
	if t == "debug":
		res = prefix + "Debug"
	elif t == "release":
		res = prefix + "Release"
	else:
		raise Exception("unknown build type %s" % t)
	return [res]

def get_compiler(t):
	prefix = "-DCMAKE_CXX_COMPILER="
	res = prefix + t
	return [res]


if __name__ == "__main__":
	args = ap.parse_args()
	prepare_binfolder()

	cmake_args = []

	cxx = args.compiler
	if cxx == None:
		if "CXX" in os.environ:
			cxx = os.environ['CXX']
	if cxx != None:
		#it seems that changing compilers requires a seperate cmake call...
		#otherwise the debug/release build info will be ignored.
		cxxchange_args = get_compiler(cxx)
		cmake_call = cmake_binary + " " + " ".join(cxxchange_args) + " .."
		print("\nswitching compiler to %s" % cxx)
		os.system(cmake_call)

	if args.mode != None:
		cmake_args += get_build_type(args.mode)

	cmake_call = cmake_binary + " " + " ".join(cmake_args) + " .."
	print("\nrunning cmake: " + cmake_call)
	os.system(cmake_call)
