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

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
OUT_DIR="${1:-$ROOT/dist}"
PACKAGE_NAME="${VIP_PACKAGE_NAME:-vip-starexec}"
STAGING="$OUT_DIR/$PACKAGE_NAME"
ARCHIVE="$OUT_DIR/$PACKAGE_NAME.tgz"

cd "$ROOT"
dune build --profile static src/main.exe

rm -rf "$STAGING"
mkdir -p "$STAGING/bin"

cp _build/default/src/main.exe "$STAGING/bin/vip"
cp starexec/starexec_run_default "$STAGING/bin/starexec_run_default"
cp starexec/starexec_run_default "$STAGING/bin/starexec_run_FOF"

chmod +x "$STAGING/bin/vip" \
  "$STAGING/bin/starexec_run_default" \
  "$STAGING/bin/starexec_run_FOF"

cat > "$STAGING/README.txt" <<EOF
VIP StarExec executable package.

Run scripts:
  bin/starexec_run_default
  bin/starexec_run_FOF

The run scripts expect the problem file as their first argument. Includes are
resolved by VIP using the current problem directory and the TPTP environment
variable when set by StarExec.

Default competition settings:
  portfolio: casc-150
  max generated clauses: 75000

The run scripts do not hardcode the CASC time limit. If StarExec or the
organizers pass a time budget, provide it either as:

  bin/starexec_run_FOF problem.p TIME_LIMIT_SECONDS
  bin/starexec_run_FOF problem.p --time-limit TIME_LIMIT_SECONDS

or through one of these environment variables:

  VIP_TIME_LIMIT, STAREXEC_TIME_LIMIT, STAREXEC_WALLCLOCK_LIMIT, TIME_LIMIT

If no time budget is supplied, VIP runs without an internal time limit and the
external StarExec wall-clock limit controls termination.

The memory limit is controlled by the StarExec job environment. CASC J13 is
expected to provide 128 GiB for the run; VIP does not request memory itself
inside the run script.
EOF

tar -C "$OUT_DIR" -czf "$ARCHIVE" "$PACKAGE_NAME"
echo "$ARCHIVE"
