#!/usr/bin/env bash
# Build / test Sylpheed Reborn inside the container.
#
# CARGO_TARGET_DIR points outside the bind-mounted repo (see the Dockerfile), so
# this never fights the host's incremental state.
#
#   build-reborn                 cargo build --workspace
#   build-reborn test            cargo test --workspace, disc tests enabled
#   build-reborn ci              fmt + clippy + test
#   build-reborn <cargo args...>
set -euo pipefail

SRC="${PROJECT_DIR:-/work}/Syplheed-Reborn"
JOBS="${SYLPH_JOBS:-2}"
cd "$SRC"

# The disc-gated integration tests self-skip when this is unset, and a green run
# then means almost nothing — point them at the extracted disc if it is there.
if [ -z "${SYLPHEED_DISC:-}" ]; then
  for c in "${PROJECT_DIR:-/work}/sylph_extract" "$SRC/../sylph_extract"; do
    [ -d "$c/dat" ] && { export SYLPHEED_DISC="$(readlink -f "$c")"; break; }
  done
fi
[ -n "${SYLPHEED_DISC:-}" ] && export SYLPHEED_RES3D="$SYLPHEED_DISC/hidden/resource3d"
if [ -z "${SYLPHEED_ISO:-}" ]; then
  iso="$(find "${PROJECT_DIR:-/work}" -maxdepth 2 -iname '*.iso' -print -quit 2>/dev/null || true)"
  [ -n "$iso" ] && export SYLPHEED_ISO="$iso"
fi
echo "==> SYLPHEED_DISC=${SYLPHEED_DISC:-<unset — disc tests will SKIP>}" >&2

export CARGO_BUILD_JOBS="$JOBS"

case "${1:-build}" in
  build) shift || true; exec cargo build --workspace "$@" ;;
  test)  shift || true; exec cargo test  --workspace "$@" ;;
  ci)
    cargo fmt --all -- --check
    cargo clippy --workspace -- -D warnings
    cargo test --workspace
    # NOTE: `just ci` also checks wasm32. That leg does not build, and not for
    # any reason in this crate: the workspace pins tokio with features=["full"],
    # which pulls mio, which refuses to compile for wasm32. Left out here rather
    # than reported as a failure of the change under test.
    echo "==> native CI green (wasm leg skipped — see the note in this script)"
    ;;
  *) exec cargo "$@" ;;
esac
