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

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

for tool in shasum xcrun cmake make codesign install_name_tool otool; do
  if ! command -v "$tool" >/dev/null 2>&1; then
    echo "error: required tool '$tool' is unavailable" >&2
    exit 1
  fi
done

(
  cd "$ROOT"
  shasum -a 256 -c SOURCE-MANIFEST.sha256
)

"$ROOT/build.sh"

helper="$ROOT/build/libraw-decoder/filmbuddy-raw-decode-libraw"
libomp="$ROOT/build/libraw-decoder/libomp.dylib"
status="$($helper status)"

for expected in \
  '"status": "ok"' \
  '"decoder": "LibRaw+librtprocess"' \
  '"libraw_version": "0.22.0-Release"'; do
  if [[ "$status" != *"$expected"* ]]; then
    echo "error: unexpected helper status payload: $status" >&2
    exit 1
  fi
done

if ! otool -L "$helper" | grep -q '@rpath/libomp\.dylib'; then
  echo "error: helper does not resolve libomp through @rpath" >&2
  exit 1
fi
if [[ "$(otool -D "$libomp" | tail -n 1)" != "@rpath/libomp.dylib" ]]; then
  echo "error: libomp install name is not @rpath/libomp.dylib" >&2
  exit 1
fi

printf '%s\n' "$status"
echo "Corresponding Source build verification passed"
