#!/bin/sh
# Builds the LGPL media helper for OMNIvour for Mac (D2): FFmpeg + LAME as universal
# (arm64 + x86_64) shared libraries plus ffmpeg/ffprobe executables, VideoToolbox and
# AudioToolbox for H.264/HEVC/AAC encode, no GPL or nonfree code. Output: dist/ (gitignored).
# Then: dist/MANIFEST.json (copy to MANIFEST.json when bumping a version on purpose).
set -eu
HERE=$(cd "$(dirname "$0")" && pwd)
. "$HERE/versions.env"
export MACOSX_DEPLOYMENT_TARGET
DIST="$HERE/dist"
# A fixed build path: FFmpeg embeds its configure line and data dir in every library, so a random
# temp dir made each build differ (review of #71). With this path and -ffile-prefix-map, two builds
# of the same pins on the same Xcode are byte-identical, and MANIFEST.json can pin them.
WORK=/tmp/omnivour-ffmpeg-build
rm -rf "$WORK" && mkdir -p "$WORK"
trap 'rm -rf "$WORK"' EXIT
REPRO="-ffile-prefix-map=$WORK=/omnivour-ffmpeg -fdebug-prefix-map=$WORK=/omnivour-ffmpeg"
JOBS=$(sysctl -n hw.ncpu)
log() { printf '== %s\n' "$*"; }

# LAME 4.0's configure insists on pkg-config even with its frontend disabled. A stand-in that
# finds no optional libraries keeps the build tool-free (no Homebrew pkg-config needed).
mkdir -p "$WORK/bin"
cat >"$WORK/bin/pkg-config" <<'SHIM'
#!/bin/sh
case "$1" in --version) echo 0.29.2 ;; --atleast-pkgconfig-version) exit 0 ;; *) exit 1 ;; esac
SHIM
chmod +x "$WORK/bin/pkg-config"
PATH="$WORK/bin:$PATH"

log "download into $WORK/src"
mkdir -p "$WORK/src"
cd "$WORK/src"
curl -sSfL -o ffmpeg.tar.xz "$FFMPEG_URL"
curl -sSfL -o lame.tar.gz "$LAME_URL"
printf '%s  ffmpeg.tar.xz\n%s  lame.tar.gz\n' "$FFMPEG_SHA256" "$LAME_SHA256" | shasum -a 256 -c -

for A in arm64 x86_64; do
    log "LAME $LAME_VERSION ($A)"
    HOST=$A
    [ "$A" = arm64 ] && HOST=aarch64          # LAME's config.sub predates the arm64 spelling
    rm -rf "$WORK/lame-src" && mkdir "$WORK/lame-src"
    tar xzf lame.tar.gz -C "$WORK/lame-src" --strip-components 1
    (
        cd "$WORK/lame-src"
        CFLAGS="-arch $A -mmacosx-version-min=$MACOSX_DEPLOYMENT_TARGET -O2 $REPRO" LDFLAGS="-arch $A" \
            ./configure --host="$HOST-apple-darwin" --prefix="$WORK/lame-$A" \
            --enable-shared --disable-static --disable-frontend --disable-decoder --disable-gtktest >"$WORK/lame-$A.log" 2>&1
        make -j"$JOBS" >>"$WORK/lame-$A.log" 2>&1 && make install >>"$WORK/lame-$A.log" 2>&1
    ) || { tail -40 "$WORK/lame-$A.log"; exit 1; }
    LAMELIB=$(cd "$WORK/lame-$A/lib" && ls libmp3lame.*.dylib | head -1)
    install_name_tool -id "@rpath/$LAMELIB" "$WORK/lame-$A/lib/$LAMELIB"

    log "FFmpeg $FFMPEG_VERSION ($A)"
    rm -rf "$WORK/ffmpeg-src" && mkdir "$WORK/ffmpeg-src"
    tar xJf ffmpeg.tar.xz -C "$WORK/ffmpeg-src" --strip-components 1
    CROSS=""
    [ "$A" = x86_64 ] && CROSS="--enable-cross-compile --disable-x86asm"
    (
        cd "$WORK/ffmpeg-src"
        # shellcheck disable=SC2086
        ./configure --prefix="$WORK/ffmpeg-$A" --datadir="$WORK/share" --arch="$A" --target-os=darwin $CROSS \
            --cc="clang -arch $A" \
            --extra-cflags="-mmacosx-version-min=$MACOSX_DEPLOYMENT_TARGET -I$WORK/lame-$A/include $REPRO" \
            --extra-ldflags="-mmacosx-version-min=$MACOSX_DEPLOYMENT_TARGET -L$WORK/lame-$A/lib" \
            --extra-ldexeflags="-Wl,-rpath,@executable_path/../Frameworks" \
            --install-name-dir='@rpath' \
            --disable-gpl --disable-nonfree --disable-version3 \
            --enable-shared --disable-static --enable-pic \
            --disable-autodetect --enable-videotoolbox --enable-audiotoolbox --enable-libmp3lame --enable-zlib \
            --disable-network --disable-avdevice --disable-doc --disable-debug --disable-ffplay \
            --disable-everything \
            --enable-protocol=file,pipe \
            --enable-demuxer=mov,matroska,avi,mp3,wav,flac,aac,ogg,asf,aiff \
            --enable-muxer=mp4,mov,matroska,avi,gif,mp3,wav,flac,adts,ipod,asf,aiff \
            --enable-decoder=h264,hevc,vp8,vp9,mpeg4,msmpeg4v3,mjpeg,prores,vc1,wmv3,rawvideo,aac,mp3float,flac,vorbis,opus,alac,wmav2,wmapro,ac3,eac3,pcm_s16le,pcm_s16be,pcm_s24le,pcm_s24be,pcm_s32le,pcm_f32le,pcm_u8,pcm_alaw,pcm_mulaw \
            --enable-encoder=h264_videotoolbox,hevc_videotoolbox,aac_at,libmp3lame,flac,gif,wmav2,pcm_s16le,pcm_s16be \
            --enable-hwaccel=h264_videotoolbox,hevc_videotoolbox \
            --enable-parser=h264,hevc,aac,mpegaudio,flac,vorbis,opus,vp8,vp9,mpeg4video \
            --enable-bsf=aac_adtstoasc,h264_mp4toannexb,hevc_mp4toannexb,extract_extradata \
            --enable-filter=scale,fps,split,palettegen,paletteuse,format,aresample,aformat,anull,null,setsar,setpts,asetpts \
            --enable-ffmpeg --enable-ffprobe >"$WORK/ffmpeg-$A.log" 2>&1
        make -j"$JOBS" >>"$WORK/ffmpeg-$A.log" 2>&1 && make install >>"$WORK/ffmpeg-$A.log" 2>&1
    ) || { tail -40 "$WORK/ffmpeg-$A.log"; exit 1; }
    cp "$WORK/lame-$A/lib/$LAMELIB" "$WORK/ffmpeg-$A/lib/"
done

log "universal binaries into $DIST"
rm -rf "$DIST" && mkdir -p "$DIST/Frameworks" "$DIST/MacOS"
for f in $(cd "$WORK/ffmpeg-arm64/lib" && ls *.dylib); do
    [ -L "$WORK/ffmpeg-arm64/lib/$f" ] && continue          # real files only; sonames resolve via @rpath
    lipo -create "$WORK/ffmpeg-arm64/lib/$f" "$WORK/ffmpeg-x86_64/lib/$f" -output "$DIST/Frameworks/$f"
done
# Keep only the soname each binary links (libavcodec.62.dylib), not the full-version file name.
for f in "$DIST"/Frameworks/*.dylib; do
    id=$(otool -D "$f" | tail -1 | sed 's|@rpath/||')
    [ "$(basename "$f")" = "$id" ] || mv "$f" "$DIST/Frameworks/$id"
done
for exe in ffmpeg ffprobe; do
    lipo -create "$WORK/ffmpeg-arm64/bin/$exe" "$WORK/ffmpeg-x86_64/bin/$exe" -output "$DIST/MacOS/$exe"
done

log "self-checks"
export DYLD_LIBRARY_PATH="$DIST/Frameworks"
FF="$DIST/MacOS/ffmpeg"
# The licence as FFmpeg itself states it (the manifest records this, not a constant).
LICENSE_TEXT=$("$FF" -hide_banner -L | tr '\n' ' ' | tr -s ' ')
case "$LICENSE_TEXT" in
    *"GNU Lesser General Public License"*"version 2.1 of the License, or"*"any later version"*) LICENSE_ID=LGPL-2.1-or-later ;;
    *) echo "FAIL: ffmpeg -L does not state LGPL 2.1 or later"; exit 1 ;;
esac
export LICENSE_ID
"$FF" -hide_banner -buildconf | grep -qE -- '--enable-(gpl|nonfree|version3)' && { echo "FAIL: GPL/nonfree/v3 flag"; exit 1; }
ENC=$("$FF" -hide_banner -encoders)
for e in h264_videotoolbox hevc_videotoolbox aac_at libmp3lame; do
    printf '%s\n' "$ENC" | grep -q " $e " || { echo "FAIL: encoder $e missing"; exit 1; }
done
printf '%s\n' "$ENC" | grep -qE ' (libx264|libx265|libfdk_aac) ' && { echo "FAIL: forbidden encoder"; exit 1; }
for f in "$DIST"/Frameworks/*.dylib "$DIST"/MacOS/*; do
    lipo -info "$f" | grep -q "x86_64 arm64\|arm64 x86_64" || { echo "FAIL: $f is not universal"; exit 1; }
    # Universal files print one "path (architecture X):" header per slice: skip header lines.
    bad=$(otool -L "$f" | grep -v ':$' | awk '{print $1}' | grep -vE '^(/usr/lib/|/System/Library/|@rpath/)' || true)
    [ -z "$bad" ] || { echo "FAIL: $f links outside the bundle: $bad"; exit 1; }
done

# Sign last: with the hardened runtime, an ad-hoc signed executable refuses ad-hoc dylibs
# ("different Team IDs"), and an executable carrying com.apple.security.inherit only runs as the
# child of a sandboxed app. Xcode re-signs everything with the team identity when it embeds them.
log "pre-sign (ad hoc; Xcode re-signs with the team on copy)"
codesign --force --sign - --options runtime "$DIST"/Frameworks/*.dylib
codesign --force --sign - --options runtime --entitlements "$HERE/inherit.entitlements" "$DIST/MacOS/ffmpeg" "$DIST/MacOS/ffprobe"

log "manifest"
python3 - "$DIST" "$HERE" <<'PY'
import hashlib, json, os, subprocess, sys
dist, here = sys.argv[1], sys.argv[2]
env = dict(l.strip().split("=", 1) for l in open(os.path.join(here, "versions.env")) if "=" in l and not l.startswith("#"))
files = {}
for sub in ("Frameworks", "MacOS"):
    for name in sorted(os.listdir(os.path.join(dist, sub))):
        path = os.path.join(dist, sub, name)
        files[f"{sub}/{name}"] = {
            "sha256": hashlib.sha256(open(path, "rb").read()).hexdigest(),
            "archs": subprocess.run(["lipo", "-archs", path], capture_output=True, text=True).stdout.split(),
            "bytes": os.path.getsize(path),
        }
xcode = subprocess.run(["xcodebuild", "-version"], capture_output=True, text=True).stdout.split("\n")[0]
manifest = {
    "license": os.environ["LICENSE_ID"],
    "ffmpeg_version": env["FFMPEG_VERSION"], "ffmpeg_sha256": env["FFMPEG_SHA256"],
    "lame_version": env["LAME_VERSION"], "lame_sha256": env["LAME_SHA256"],
    "lgpl_components": [f"FFmpeg {env['FFMPEG_VERSION']}", f"LAME {env['LAME_VERSION']}"],
    "built_with": xcode, "macos_min": env["MACOSX_DEPLOYMENT_TARGET"],
    "total_bytes": sum(f["bytes"] for f in files.values()),
    "files": files,
}
json.dump(manifest, open(os.path.join(dist, "MANIFEST.json"), "w"), indent=2, sort_keys=True)
print("total MB:", round(manifest["total_bytes"] / 1e6, 1))
PY
log "done: $DIST"
