#!/usr/bin/env bash

set -euo pipefail

package_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
source_dir="$package_dir/_ref_av1_aom"
build_dir="${1:-$source_dir/build_enc}"

if [[ ! -f "$source_dir/CMakeLists.txt" ]]; then
  echo "AOM source tree not found at: $source_dir" >&2
  exit 1
fi

if [[ -n "${BUILD_JOBS:-}" ]]; then
  build_jobs="$BUILD_JOBS"
elif command -v nproc >/dev/null 2>&1; then
  build_jobs="$(nproc)"
else
  build_jobs="$(getconf _NPROCESSORS_ONLN 2>/dev/null || echo 4)"
fi

cmake \
  -S "$source_dir" \
  -B "$build_dir" \
  -DCONFIG_AV1_ENCODER=1 \
  -DCONFIG_AV1_DECODER=0 \
  -DENABLE_EXAMPLES=1 \
  -DENABLE_TOOLS=0 \
  -DENABLE_TESTS=0 \
  -DCMAKE_BUILD_TYPE=Release \
  -DAOM_TARGET_CPU=generic

cmake --build "$build_dir" --target aomenc --parallel "$build_jobs"

echo
echo "Built: $build_dir/aomenc"
"$build_dir/aomenc" --help 2>&1 | grep -- '--tools-cfg' || {
  echo "Build completed, but --tools-cfg is missing from aomenc." >&2
  exit 1
}
