#!/usr/bin/python3

from shutil import rmtree, copy
from os import mkdir, chdir, listdir, remove, rename
from os.path import isdir
from stuff import compile_cpp

from sys import exit, argv

import subprocess

if len(argv) < 2:
    print('Pass solution source as an argument: check_cpp.py solutions/turtles_ma_qlogn.cpp')
    exit(1)

SOLUTION_SRC = argv[1]
CHECK_SRC = 'check.cpp'

if not isdir('./bin'):
    mkdir('bin')

chdir('bin')

for f in filter(lambda x : len(x) == 2, sorted(listdir())):
    remove(f)


compile_cpp('../' + SOLUTION_SRC, './sol')
compile_cpp('../' + CHECK_SRC, './check')

for f in filter(lambda x : len(x) == 2, sorted(listdir('../tests'))):
    print('Running on', f)
    copy('../tests/' + f, 'turtles.in')
    copy('../tests/' + f + '.a', 'turtles.ans')
    code = subprocess.call(['./sol'], stdin=open('turtles.in', 'r'))
    if code != 0:
        print("Error while running on", f)
        exit(1)
    code = subprocess.call(['./check', 'turtles.in', 'turtles.out', 'turtles.ans'])
    if code != 0:
        print("Error while checking on", f)
        exit(1)

remove('turtles.in')
remove('turtles.out')

print('\nFinished!')
