#!/usr/bin/env python3
import platform
import os
import sys

if platform.system() == 'Darwin':
    os.system('clang -std=c99 -lm -Oz -o mother main.c mother.c')
else:
    debug = False
    package = False

    if len(sys.argv) > 1:
        for arg in sys.argv[1:]:
            if arg == 'debug':
                debug = True
            elif arg == 'package':
                package = True
            else:
                print('Warning: Unrecognized build flag "' + arg + '".')

    CCPARAMS=''

    if debug:
        CCPARAMS = '-Walloc-zero -Wall -DDEBUG -O0 -ggdb3'
        CCPARAMS += ' -fbounds-check -fsanitize=address -fsanitize=undefined -fsanitize=shift -fsanitize=shift-exponent -fsanitize=integer-divide-by-zero -fsanitize=signed-integer-overflow -fsanitize=bounds-strict -fsanitize=alignment -fsanitize=object-size -fsanitize=builtin -fno-sanitize-recover=all -fsanitize=float-divide-by-zero -fsanitize=float-cast-overflow -fno-sanitize=null -fno-sanitize=alignment'
    else:
        OPTPARAMS='-std=gnu11 -m64 -march=nehalem -mfpmath=sse -no-pie -fno-pic -ffast-math -fmerge-all-constants -fno-unwind-tables -fno-asynchronous-unwind-tables'
        CCPARAMS = OPTPARAMS + ' -Wall -fno-unroll-loops -fno-stack-protector -fno-stack-check -fomit-frame-pointer -Oz'

    os.system('gcc ' + CCPARAMS + ' -c -o main.o main.c')
    os.system('gcc ' + CCPARAMS + ' -c -o mother.o mother.c')

    if os.path.exists('main.o') and os.path.exists('mother.o'):
        os.system('gcc ' + CCPARAMS + ' -lm -o mother main.o mother.o')

    if os.path.exists('mother.o'):
        os.system('xz -z -e -9 -f -k mother.o')
        os.system('wc mother.o.xz')
        os.system('rm mother.o.xz')
