#!/usr/bin/env bash
# Inject LGPL VobSub muxer into the FFmpeg source tree before configure.
set -euo pipefail

SOURCE_TREE="${1:?FFmpeg source tree path required}"
PATCH_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

if [[ ! -d "$SOURCE_TREE/libavformat" ]]; then
  echo "ERROR: Invalid FFmpeg source tree: $SOURCE_TREE" >&2
  exit 1
fi

cp -f "${PATCH_DIR}/vobsubenc.c" "${SOURCE_TREE}/libavformat/vobsubenc.c"

if ! grep -q "ff_vobsub_muxer" "${SOURCE_TREE}/libavformat/allformats.c"; then
  sed -i '' '/^extern const FFInputFormat  ff_vobsub_demuxer;$/a\
extern const FFOutputFormat ff_vobsub_muxer;
' "${SOURCE_TREE}/libavformat/allformats.c"
fi

if ! grep -q "vobsubenc.o" "${SOURCE_TREE}/libavformat/Makefile"; then
  sed -i '' '/^OBJS-$(CONFIG_VOBSUB_DEMUXER)/a\
OBJS-$(CONFIG_VOBSUB_MUXER)                 += vobsubenc.o
' "${SOURCE_TREE}/libavformat/Makefile"
fi

echo "Applied VobSub muxer patch to ${SOURCE_TREE}"
