#!/bin/sh
# Holds a configured FFmpeg tree to components.env: fails when the
# configuration enables a component the list does not name, or lacks one it
# does. Run by every recipe after ./configure and before make.
#
#   check-components.sh <macos|linux|windows> <path to config_components.h>
set -eu
HERE="$(cd "$(dirname "$0")" && pwd)"
. "$HERE/components.env"
system="${1:-}"; header="${2:-}"
case "$system" in
  macos)   sys_encoders="$ENCODERS_MACOS";   sys_hwaccels="$HWACCELS_MACOS";   sys_protocols="$PROTOCOLS_MACOS" ;;
  linux)   sys_encoders="$ENCODERS_LINUX";   sys_hwaccels="$HWACCELS_LINUX";   sys_protocols="$PROTOCOLS_LINUX" ;;
  windows) sys_encoders="$ENCODERS_WINDOWS"; sys_hwaccels="$HWACCELS_WINDOWS"; sys_protocols="$PROTOCOLS_WINDOWS" ;;
  *) echo "usage: $0 <macos|linux|windows> <config_components.h>" >&2; exit 2 ;;
esac
[ -r "$header" ] || { echo "cannot read $header" >&2; exit 2; }

# enabled CLASS: the lowercased names config_components.h enables in CLASS.
enabled() {
  sed -n "s/^#define CONFIG_\\(.*\\)_$1 1\$/\\1/p" "$header" | tr 'A-Z' 'a-z' | LC_ALL=C sort -u
}
listed() { printf '%s\n' $1 | sed '/^$/d' | LC_ALL=C sort -u; }

tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT
bad=0
# hold CLASS "names...": the configuration's CLASS is exactly these names.
hold() {
  class="$1"
  listed "$2" > "$tmp/want"
  enabled "$class" > "$tmp/have"
  extra="$(LC_ALL=C comm -23 "$tmp/have" "$tmp/want")"
  missing="$(LC_ALL=C comm -13 "$tmp/have" "$tmp/want")"
  if [ -n "$extra" ]; then
    echo "ERROR: $class outside components.env: $(echo $extra)" >&2; bad=1
  fi
  if [ -n "$missing" ]; then
    echo "ERROR: $class named in components.env and not configured: $(echo $missing)" >&2; bad=1
  fi
}

hold DEMUXER  "$DEMUXERS $PULLED_DEMUXERS"
hold DECODER  "$DECODERS $PULLED_DECODERS"
hold PARSER   "$PARSERS $PULLED_PARSERS"
hold BSF      "$BSFS $PULLED_BSFS"
hold MUXER    "$MUXERS $PULLED_MUXERS"
hold ENCODER  "$ENCODERS $sys_encoders $PULLED_ENCODERS"
hold FILTER   "$FILTERS $PULLED_FILTERS"
hold HWACCEL  "$sys_hwaccels $PULLED_HWACCELS"
hold PROTOCOL "$PROTOCOLS $sys_protocols $PULLED_PROTOCOLS"
hold INDEV    "lavfi"
hold OUTDEV   ""
[ "$bad" = 0 ] || exit 1
echo "    the configuration holds exactly the components components.env names"
