import platform

CC = 'gcc'
system = platform.system()
mac_ver = platform.mac_ver()

# gcc installed by homebrew has version suffix (e.g. gcc-12) in order to be
# distinguishable from system one - which acts as a symlink to clang
# clang works on macOS 15 and greater but has issues on earlier macOS versions.
# see: https://github.com/commaai/openpilot/issues/35093
if system == 'Darwin' and mac_ver[0] and mac_ver[0] < '15':
  CC += '-13'

# standard env
env = Environment(
  CC=CC,
  CFLAGS=[
    '-Wall',
    "-Wextra",
    '-Werror',
    '-nostdlib',
    '-fno-builtin',
    '-std=gnu11',
    '-Wfatal-errors',
    '-Wno-pointer-to-int-cast',
    '-g',
    '-O0',
    '-fno-omit-frame-pointer',
    '-fprofile-arcs',
    '-ftest-coverage',
    '-DALLOW_DEBUG',
  ],
  LINKFLAGS=[
    '-fprofile-arcs',
    '-ftest-coverage',
  ],
  CPPPATH=["#", "../../board/"],
  tools=["default", "compilation_db"],
)
if system == "Darwin":
  env.PrependENVPath('PATH', '/opt/homebrew/bin')
if GetOption('ubsan'):
  env.Prepend(LINKFLAGS=[
    "-fsanitize=undefined",
    "-fno-sanitize-recover=undefined",
  ])

# mutation env
menv = env.Clone()
menv['CC'] = 'clang-17'
flags = [
  '-fprofile-instr-generate',
  '-fcoverage-mapping',
  '-fpass-plugin=/usr/lib/mull-ir-frontend-17',
  '-g',
  '-grecord-command-line',
]
menv['CFLAGS'] += flags
menv['LINKFLAGS'] += flags

for build_env, suffix in ((env, ""), (menv, "_mutation")):
  # TODO: add macOS support
  if (build_env == menv) and (system == "Darwin"):
    continue
  safety = env.SharedObject(f"safety{suffix}.os", "safety.c")
  libsafety = env.SharedLibrary(f"libsafety{suffix}.so", [safety])

  # GCC note file is generated by compiler, allow scons to clean it up
  env.SideEffect("safety.gcno", safety)
