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

if [[ "$#" -ne 2 ]]; then
    echo "usage: $0 <formula.cnf> <out.proof>" >&2
    exit 2
fi

FORMULA="$1"
OUT_PROOF="$2"
IMAGE="lymphosat-export-solver"

if [[ ! -f "$FORMULA" ]]; then
    echo "formula not found: $FORMULA" >&2
    exit 2
fi

TMP_DIR="$(mktemp -d)"
cleanup() {
    rm -rf "$TMP_DIR"
}
trap cleanup EXIT

mkdir -p "$TMP_DIR/out"
cp "$FORMULA" "$TMP_DIR/formula.cnf"

set +e
docker run --platform linux/amd64 --rm \
    -v "$TMP_DIR:/io" \
    "$IMAGE" \
    ./run.sh /io/formula.cnf /io/out
rc=$?
set -e

mkdir -p "$(dirname "$OUT_PROOF")"
if [[ -f "$TMP_DIR/out/proof.out" ]]; then
    cp "$TMP_DIR/out/proof.out" "$OUT_PROOF"
else
    : > "$OUT_PROOF"
fi

if [[ "$rc" != 0 && "$rc" != 10 && "$rc" != 20 ]]; then
    echo "run.sh exited with unexpected code $rc for $FORMULA" >&2
fi
exit "$rc"
