#!/bin/bash

function die() {
    echo "fatal: $*" >&2
    exit 1
}

function try() {
    "$@" || die "failed: $*"
}


id="`grep 'id' ../problem.properties | awk '{ print $3; }'`"
[ -n "$id" ] || die "no id in problem.properties"

echo "problem: $id"

try mkdir -p '../tests/'

echo "generate tests"
try bash do_tests.sh

tests=()
for x in ../tests/??; do
    [ -f "$x" ] || continue
    tests[${#tests[*]}]="$x"
done
echo "tests found: ${#tests[*]}"

echo "validate tests"
try g++ -O2 -Wall -Wextra -Werror -o validate -x c++ validate.c++
for x in "${tests[@]}"; do
    try ./validate < "$x"
done

solution="`grep 'solution' ../problem.properties | awk '{ print $3; }'`"
[ -n "$solution" ] && [ -f "../$solution" ] || die "solution not found (name='$solution')"
echo "generate answers"
try g++ -O2 -Wall -Wextra -Werror -o solution -x c++ "../$solution"
for x in "${tests[@]}"; do
    try cp "$x" "${id}.in"
    try ./solution
    [ -f "${id}.out" ] || die "not output file '${id}.out' found"
    try cp "${id}.out" "${x}.a"
done

try rm "${id}.in" "${id}.out"
rm solution || rm solution.exe
