#!/usr/bin/env bash
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
IMAGE="lymphosat-export-competition"
CONTAINER=""

cleanup() {
    if [[ -n "$CONTAINER" ]]; then
        docker rm -f "$CONTAINER" >/dev/null 2>&1 || true
    fi
}
trap cleanup EXIT

docker build --platform linux/amd64 -f "$ROOT/competition.Dockerfile" -t "$IMAGE" "$ROOT"
CONTAINER="$(docker run --platform linux/amd64 -d --rm -v "$ROOT:/tool" -w /tool "$IMAGE" sleep infinity)"

docker exec "$CONTAINER" ./build.sh

shopt -s nullglob
cnfs=("$ROOT"/tests/*.cnf)
if (( ${#cnfs[@]} == 0 )); then
    echo "no CNF tests found under tests/" >&2
    exit 2
fi

for cnf in "${cnfs[@]}"; do
    name="$(basename "$cnf")"
    out_dir="/tmp/lymphosat-export-test/${name%.cnf}"
    echo "running tests/$name"
    docker exec "$CONTAINER" rm -rf "$out_dir"
    docker exec "$CONTAINER" mkdir -p "$out_dir"
    set +e
    docker exec "$CONTAINER" ./run.sh "tests/$name" "$out_dir"
    rc=$?
    set -e
    if [[ "$rc" != 0 && "$rc" != 10 && "$rc" != 20 ]]; then
        echo "run.sh exited with unexpected code $rc for tests/$name" >&2
        exit "$rc"
    fi
done
