'''Build binary, run unit tests and other tests against *.in'''
import os
import re
import glob

if False:
    Environment = None

env = Environment()


def envcmd(t, s, c, p):
    env.Command(t, s, c + ' ' + p)
    env.Depends(t, c)

solversrc = glob.glob('solver.c*')[0]
solver = re.sub('\.c(pp|c)?$', '', solversrc)
env.Program(solversrc, CPPFLAGS='-Wall -Werror -W -g -std=c++11')

outputs = []


def tests_setup():
    env.Library('gtest', 'gtest.cc', CXXFLAGS='-I/usr/src/gtest')
    env.Program('tests',
                ['tests.cc'],
                LIBS=['pthread', 'gtest.a'],
                LIBPATH='.',
                CPPFLAGS='-Wall -Werror -W -g -std=c++11')
    envcmd('tests_output.txt', [], './tests', '2>&1 | tee $TARGET')
    outputs.append('tests_output.txt')
if os.path.exists('tests.cc'):
    tests_setup()


def inproc(i):
    b = re.sub('\.in$', '', i)
    o = b + '.out'
    envcmd(o, i, './' + solver, ' $SOURCE $TARGET')
    outputs.append(o)
    if os.path.exists(b + '.ans'):
        env.Command(b + '.done', o, 'diff $SOURCE %s && md5sum $SOURCE > $TARGET' %
                    (b + '.ans'))
        env.Depends(b + '.done', b + '.ans')

for i in glob.glob('*.in'):
    inproc(i)


def showpaths(target, source, env):
    for s in source:
        print(os.path.abspath(str(s)))
env.Command('all-done.txt', outputs, showpaths)
