#!/bin/env python3

from subprocess import getoutput, run
from os import getcwd
from os.path import expandvars
from pathlib import Path
from sys import argv
import tomllib

has_ninja = getoutput("command -v ninja") != ""
has_clang = getoutput("command -v clang") != ""

#TODO: support for default pack override

cmake = ["cmake"]
# check whether clang is around (it's just better)
if has_clang:
    cmake += ["-DCMAKE_C_COMPILER=clang"]
# check whether ninja is around (you better start running)
if has_ninja:
    cmake += ["-G", "Ninja"]
cmake += ["-B", "build"]
# TODO: have it --fast instead, where separate --no-debug would mean stripping the debug info
if "--release" in argv:
    cmake += ["-DCMAKE_BUILD_TYPE=Release"]
cmake += [f"-DTWN_OUT_DIR={getcwd()}"]
# pass arbitrary arguments over
if "--" in argv:
    cmake += argv[argv.index("--")+1:]

# if no root cmake file is present, infer it from `twn.toml:game.interpreter`
if not Path("CMakeLists.txt").is_file():
    config = tomllib.loads(Path("data/twn.toml").read_text())
    cmake += ["-S", expandvars(config["game"]["interpreter"])]

run(cmake, check=True)
run(["cmake", "--build", "build", "--parallel"], check=True)
