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

# Add an arm64 Mac Catalyst slice to the vendored FFmpegKitNext v9.0.0
# XCFrameworks. Same pinned sources, patches and LGPL flags as
# build-ffmpegkit-next-v9-ios.sh; the existing iOS device and simulator slices
# are carried over byte for byte (checked below). Run from any cwd:
#   scripts/build-ffmpegkit-next-v9-maccatalyst.sh /absolute/path/to/ios/KCPhone/Vendor
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
frameworks=(ffmpegkit libavcodec libavdevice libavfilter libavformat libavutil libswresample libswscale)
test -d "$target_dir" || { echo "missing vendor: $target_dir" >&2; exit 1; }
for name in "${frameworks[@]}"; do
  for slice in ios-arm64 ios-arm64-simulator; do
    test -d "$target_dir/$name.xcframework/$slice/$name.framework" || {
      echo "missing $slice slice in $name.xcframework" >&2; exit 1; }
  done
done
for tool in git xcodebuild python3 brew pkgconf autoconf automake libtool vtool; 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-catalyst.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
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"
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-mac-catalyst \
    --target=15.0 --mac-catalyst-target=15.0 --no-bitcode --enable-lib-openssl -x --spm --jobs=6 \
    > "$build_dir/catalyst-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

built=$build_dir/source/prebuilt/bundle-apple-xcframework-ios-15.0
format=$built/libavformat.xcframework/ios-arm64-maccatalyst/libavformat.framework/Versions/A/libavformat
vtool -show-build "$format" | grep -q "platform MACCATALYST"
grep -q KC_FFMPEG_ALLOWED_HOSTS "$format"

staging_dir=$vendor_dir/.FFmpegKitNext-v9.0.0.catalyst.$$
test ! -e "$staging_dir" || { echo "staging exists: $staging_dir" >&2; exit 1; }
mkdir -p "$staging_dir"
for item in LICENSE.FFmpegKitNext Package.swift Resources SOURCE_LOCK.md; do
  ditto "$target_dir/$item" "$staging_dir/$item"
done
for name in "${frameworks[@]}"; do
  catalyst=$built/$name.xcframework/ios-arm64-maccatalyst/$name.framework
  test -d "$catalyst" || { echo "missing catalyst build of $name" >&2; exit 1; }
  xcodebuild -create-xcframework \
    -framework "$target_dir/$name.xcframework/ios-arm64/$name.framework" \
    -framework "$target_dir/$name.xcframework/ios-arm64-simulator/$name.framework" \
    -framework "$catalyst" \
    -output "$staging_dir/$name.xcframework" >/dev/null
  for slice in ios-arm64 ios-arm64-simulator; do
    diff -r "$target_dir/$name.xcframework/$slice" "$staging_dir/$name.xcframework/$slice" >/dev/null || {
      echo "$name $slice changed while merging" >&2; exit 1; }
  done
done

python3 - "$staging_dir/Package.swift" <<'PY'
import sys
path = sys.argv[1]
text = open(path).read()
if '.macCatalyst(' not in text:
    text = text.replace('.iOS("15.0"),', '.iOS("15.0"),\n        .macCatalyst("15.0"),', 1)
open(path, "w").write(text)
PY
cat >> "$staging_dir/SOURCE_LOCK.md" <<'MD'

## Mac Catalyst slice (KC-X Mac)

Added by `scripts/build-ffmpegkit-next-v9-maccatalyst.sh` from the same
ffmpeg-kit-next, FFmpeg and OpenSSL commits and the same two patches, with
`--arch=arm64-mac-catalyst --target=15.0 --mac-catalyst-target=15.0
--no-bitcode --enable-lib-openssl -x --spm`; no `--enable-gpl`. Each
XCFramework gains `ios-arm64-maccatalyst`; the `ios-arm64` and
`ios-arm64-simulator` slices are copied unchanged from the iOS build. The
Catalyst `libavformat` carries the `KC_FFMPEG_ALLOWED_HOSTS` marker.
MD
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 "$target_dir" "$build_dir/previous-vendor"
mv "$staging_dir" "$target_dir"
echo "updated vendor: $target_dir"
echo "previous vendor kept at: $build_dir/previous-vendor"
echo "build log: $build_dir/catalyst-build.log"
