#!/bin/bash
set -euo pipefail

# Build the separate LGPL FFmpeg executable used inside the App Store sandbox.
# Pass the path to the extracted and verified FFmpeg 8.0.1 release source.
source_root="$(cd "${1:?Usage: build-ffmpeg.sh /path/to/ffmpeg-8.0.1}" && pwd)"
out_root="$(cd "$(dirname "$0")/.." && pwd)/build/store-ffmpeg"
sdk="$(xcrun --sdk macosx --show-sdk-path)"
mkdir -p "$out_root"

for arch in arm64 x86_64; do
    mkdir -p "$out_root/$arch"
    (
        cd "$out_root/$arch"
        "$source_root/configure" --arch="$arch" --target-os=darwin --enable-cross-compile \
            --sysroot="$sdk" --extra-cflags="-arch $arch -mmacosx-version-min=14.0" \
            --extra-ldflags="-arch $arch -mmacosx-version-min=14.0" \
            --disable-autodetect --disable-doc --disable-debug --disable-x86asm \
            --disable-gpl --disable-nonfree --disable-everything \
            --disable-ffprobe --disable-ffplay --enable-ffmpeg --enable-securetransport \
            --enable-protocol=file,pipe,tcp,tls,udp,rtp \
            --enable-demuxer=rtsp,sdp --enable-muxer=rawvideo \
            --enable-decoder=h264,hevc --enable-parser=h264,hevc \
            --enable-encoder=rawvideo --enable-filter=fps,scale,pad,setsar
        make -j "${BAMBUCAM_BUILD_JOBS:-10}" ffmpeg
    )
done
lipo -create "$out_root/arm64/ffmpeg" "$out_root/x86_64/ffmpeg" -output "$out_root/ffmpeg"
cp "$source_root/COPYING.LGPLv2.1" "$out_root/FFmpeg-LGPL-2.1.txt"
lipo -archs "$out_root/ffmpeg"
