#!/usr/bin/env bash
# Rebuild the audio comparison core from the corresponding source archives.
# Usage: EMSDK_ENV=/path/to/emsdk_env.sh bash build-lgpl-core.sh /path/to/output
set -euo pipefail

here=$(cd "$(dirname "$0")" && pwd)
output=${1:?Specify an output directory}
mkdir -p "$output"
output=$(cd "$output" && pwd)
: "${EMSDK_ENV:?Set EMSDK_ENV to the emsdk_env.sh for Emscripten 3.1.40}"
source "$EMSDK_ENV" >/dev/null
if ! emcc --version | head -n 1 | grep -q '3.1.40'; then
    echo 'Emscripten 3.1.40 is required.' >&2
    exit 1
fi

work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
tar -xzf "$here/source/FFmpeg-n5.1.4.tar.gz" -C "$work"
tar -xzf "$here/source/lame-2badea19.tar.gz" -C "$work"
tar -xzf "$here/source/ffmpeg-wasm-v12.15.tar.gz" -C "$work"
install_dir="$work/install"

cd "$work/lame-2badea19"
export CFLAGS='-O2'
emconfigure ./configure \
    --prefix="$install_dir" --host=i686-linux --disable-shared \
    --disable-decoder --disable-frontend --disable-analyzer-hooks \
    --disable-dependency-tracking --disable-gtktest
emmake make -j4
emmake make install

cd "$work/FFmpeg-n5.1.4"
export INSTALL_DIR="$install_dir"
export FFMPEG_ST=yes
export CFLAGS="-O2 -I$install_dir/include"
export CXXFLAGS="$CFLAGS"
export LDFLAGS="-L$install_dir/lib"
export EM_PKG_CONFIG_PATH="$install_dir/lib/pkgconfig"
bash "$work/ffmpeg-wasm-v12.15/build/ffmpeg.sh" \
    --enable-libmp3lame --disable-gpl --disable-nonfree --disable-postproc
grep -q '^#define CONFIG_GPL 0$' config.h
grep -q '^#define CONFIG_NONFREE 0$' config.h
grep -q '^#define FFMPEG_LICENSE "LGPL version 2.1 or later"$' config.h
grep -q '^/\* #undef HAVE_MPGLIB \*/$' "$work/lame-2badea19/config.h"

mkdir -p src
cp -R "$work/ffmpeg-wasm-v12.15/src/bind" src/
cp -R "$work/ffmpeg-wasm-v12.15/src/fftools" src/
exports=$(node src/bind/ffmpeg/export.js)
runtime_exports=$(node src/bind/ffmpeg/export-runtime.js)

# The upstream CLI binding is retained. SDL and libpostproc are excluded.
emcc \
    -I. -I./src/fftools -I"$install_dir/include" \
    -L"$install_dir/lib" -Llibavcodec -Llibavdevice -Llibavfilter \
    -Llibavformat -Llibavutil -Llibswresample -Llibswscale \
    -lavcodec -lavdevice -lavfilter -lavformat -lavutil \
    -lswresample -lswscale -lmp3lame \
    -Wno-deprecated-declarations \
    -sENVIRONMENT=worker -sWASM_BIGINT -sSTACK_SIZE=5MB \
    -sMODULARIZE -sINITIAL_MEMORY=32MB -sALLOW_MEMORY_GROWTH \
    -sEXPORT_NAME=createFFmpegCore \
    -sEXPORTED_FUNCTIONS="$exports" \
    -sEXPORTED_RUNTIME_METHODS="$runtime_exports" \
    -lworkerfs.js --pre-js src/bind/ffmpeg/bind.js \
    src/fftools/cmdutils.c src/fftools/ffmpeg.c \
    src/fftools/ffmpeg_filter.c src/fftools/ffmpeg_hw.c \
    src/fftools/ffmpeg_mux.c src/fftools/ffmpeg_opt.c \
    src/fftools/opt_common.c src/fftools/ffprobe.c \
    -o "$output/ffmpeg-core.js"

shasum -a 256 "$output/ffmpeg-core.js" "$output/ffmpeg-core.wasm"
