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

# Run with Emscripten SDK 3.1.40 already activated. Point these at the two
# separately extracted source archives provided alongside this script.
: "${FFMPEG_DIR:?Set FFMPEG_DIR to the extracted FFmpeg 5.1.4 directory}"
: "${WRAPPER_DIR:?Set WRAPPER_DIR to the extracted ffmpeg.wasm source directory}"
: "${OUTPUT_DIR:?Set OUTPUT_DIR to a writable output directory}"
script_dir="$(cd "$(dirname "$0")" && pwd)"
mkdir -p "$OUTPUT_DIR"
output_dir="$(cd "$OUTPUT_DIR" && pwd)"
cd "$FFMPEG_DIR"
cp -R "$WRAPPER_DIR/src" ./src
emconfigure ./configure --target-os=none --arch=x86_32 --enable-cross-compile \
  --disable-asm --disable-stripping --disable-programs --disable-doc --disable-debug \
  --disable-runtime-cpudetect --disable-autodetect --disable-pthreads --disable-w32threads \
  --disable-os2threads --disable-everything --enable-avcodec --enable-avformat \
  --enable-avfilter --enable-avutil --enable-swresample --enable-swscale \
  --enable-avdevice --enable-postproc --enable-decoder=gif --enable-encoder=gif \
  --enable-demuxer=gif --enable-muxer=gif --enable-protocol=file \
  --enable-filter=fps,scale,split,palettegen,paletteuse,format,buffer,buffersink \
  --nm=emnm --ar=emar --ranlib=emranlib --cc=emcc --cxx=em++ --objcc=emcc \
  --dep-cc=emcc --extra-cflags=-O3
emmake make -j4
export FFMPEG_ST=1 FFMPEG_MT='' INSTALL_DIR="$output_dir" LDFLAGS=-O3
bash "$script_dir/link.sh" -sEXPORT_ES6 -o "$output_dir/ffmpeg-core.js"
