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

# Rebuild the exact LGPL (no --enable-gpl) iOS candidate. Run from any cwd:
# ./build-vendor.sh /absolute/path/to/ios/KCPhone/Vendor
# The output is self-contained; Xcode must never reference /tmp paths.
if [[ $# -ne 1 || $1 != /* ]]; then
  echo "usage: $0 ABSOLUTE_VENDOR_DIRECTORY" >&2
  exit 2
fi
vendor_dir=$1
script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
target_dir=$vendor_dir/FFmpegKitNext-v9.0.0
if [[ -e $target_dir ]]; then
  echo "target already exists: $target_dir" >&2
  exit 1
fi
for tool in git xcodebuild swift python3 brew pkgconf autoconf automake libtool; do
  command -v "$tool" >/dev/null || { echo "missing tool: $tool" >&2; exit 1; }
done
gnu_sed_bin=$(brew --prefix gnu-sed)/libexec/gnubin
test -x "$gnu_sed_bin/sed" || { echo "GNU sed missing" >&2; exit 1; }

build_dir=$(mktemp -d "${TMPDIR:-/tmp}/kc-ffmpeg-next.XXXXXXXX")
echo "build directory: $build_dir"
git clone --quiet --branch v9.0.0 --depth 1 \
  https://github.com/arthenica/ffmpeg-kit-next.git "$build_dir/source"
test "$(git -C "$build_dir/source" rev-parse HEAD)" = \
  a724ed99583dcfe2af497c794fdd6b24ddd54a4e
# Upstream exception handling logs complete session arguments on failure.
# Remove that path before any binary is built or packaged.
git -C "$build_dir/source" apply --check "$script_dir/ffmpegkit-redact-args.patch"
git -C "$build_dir/source" apply "$script_dir/ffmpegkit-redact-args.patch"
# Donor's ios.sh treats an existing pinned FFmpeg source as downloaded.
# Apply the reviewed host guard before the first iOS framework build.
git clone --quiet --branch n9.0.1 --depth 1 \
  https://github.com/arthenica/FFmpeg.git "$build_dir/source/src/ffmpeg"
test "$(git -C "$build_dir/source/src/ffmpeg" rev-parse HEAD)" = \
  bf1b838f2ab88b4f8fd83443325c782ea0e0f7fa
git -C "$build_dir/source/src/ffmpeg" apply --check "$script_dir/ffmpeg-http-hostguard.patch"
git -C "$build_dir/source/src/ffmpeg" apply "$script_dir/ffmpeg-http-hostguard.patch"
(
  cd "$build_dir/source"
  PATH="$gnu_sed_bin:$PATH" ./ios.sh --arch=arm64,arm64-simulator \
    --target=15.0 --no-bitcode --enable-lib-openssl -x --spm --jobs=4 \
    > "$build_dir/ios-build.log" 2>&1
)
test "$(git -C "$build_dir/source/src/ffmpeg" rev-parse HEAD)" = \
  bf1b838f2ab88b4f8fd83443325c782ea0e0f7fa
test "$(git -C "$build_dir/source/src/openssl" rev-parse HEAD)" = \
  8cf17aaeb4599f8af87fefd810b5b5fee90fe69e

git clone --quiet --branch v9.0.0 --depth 1 \
  https://github.com/arthenica/ffmpeg-kit-next-test.git "$build_dir/test-source"
test "$(git -C "$build_dir/test-source" rev-parse HEAD)" = \
  a4dc3a641d785dfe09267923283263a66e27aafa
ca_source=$build_dir/test-source/ios/Resources/cacert_2026_08_13.pem
test "$(shasum -a 256 "$ca_source" | awk '{print $1}')" = \
  f66dff1bdf8f96060b8177976f8b7d9254bc89bc4db933d769f7384d28480bc9

mkdir -p "$vendor_dir"
staging_dir=$vendor_dir/.FFmpegKitNext-v9.0.0.staging.$$
if [[ -e $staging_dir ]]; then
  echo "staging target already exists: $staging_dir" >&2
  exit 1
fi
mkdir -p "$staging_dir/Resources"
ditto "$build_dir/source/prebuilt/bundle-apple-xcframework-ios-15.0" "$staging_dir"
cp "$ca_source" "$staging_dir/Resources/"
cp "$build_dir/test-source/ios/Resources/mozilla_ca_bundle_license.txt" \
  "$staging_dir/Resources/"
cp "$build_dir/source/LICENSE" "$staging_dir/LICENSE.FFmpegKitNext"
cp "$script_dir/FFmpegKitNext-v9-SOURCE_LOCK.md" "$staging_dir/SOURCE_LOCK.md"
(cd "$staging_dir" && swift package dump-package >/dev/null)
# SwiftPM creates a transient cache during package validation. It is not a
# reproducible source or framework artifact and must not enter the lock.
rm -rf "$staging_dir/.build"
python3 - "$staging_dir" <<'PY'
from pathlib import Path
import hashlib, sys
root = Path(sys.argv[1])
lines = []
for path in sorted(root.rglob("*")):
    if path.is_file() and not path.is_symlink():
        lines.append(f"{hashlib.sha256(path.read_bytes()).hexdigest()}  {path.relative_to(root).as_posix()}")
(root / "BUILD_ARTIFACT.sha256").write_text("\n".join(lines) + "\n")
PY
mv "$staging_dir" "$target_dir"
echo "built vendor: $target_dir"
echo "build log: $build_dir/ios-build.log"
echo "source tree retained for audit: $build_dir/source"
