#!/usr/bin/env bash
# CI entry point with separate build and unit-test modes.
set -euo pipefail

usage() {
  echo "Usage: bash build.sh [build|ut] [additional Maven options]"
  echo "  build  Compile and package the JAR without compiling/running tests (default)."
  echo "  ut     Compile and run unit tests without packaging the JAR."
}

MODE="${1:-build}"
if [[ $# -gt 0 ]]; then
  shift
fi
case "${MODE}" in
  build)
    MAVEN_ARGS=(-Dmaven.test.skip=true clean package)
    ;;
  ut)
    MAVEN_ARGS=(-DskipTests=false -Dmaven.test.skip=false -Dmaven.test.failure.ignore=false -DfailIfNoTests=true clean test)
    ;;
  -h|--help)
    usage
    exit 0
    ;;
  *)
    echo "Error: unknown mode '${MODE}'." >&2
    usage >&2
    exit 2
    ;;
esac

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
if ! command -v mvn >/dev/null 2>&1; then
  echo "Error: Maven 3.9+ is required; install Maven and add mvn to PATH." >&2
  exit 1
fi

# Resolve the project independently of the caller's working directory.
# Preserve Maven's exit code so compilation/test failures fail the CI job.
exec mvn --batch-mode --no-transfer-progress --show-version \
  --file "${PROJECT_DIR}/pom.xml" "$@" "${MAVEN_ARGS[@]}"