#!/bin/zsh

set -euo pipefail

ROOT="${0:A:h:h}"
VERSION="8.1.2"
SOURCE_URL="https://ffmpeg.org/releases/ffmpeg-${VERSION}.tar.xz"
SOURCE_SHA256="464beb5e7bf0c311e68b45ae2f04e9cc2af88851abb4082231742a74d97b524c"

DEPS_ROOT="${DROIDLUME_MAS_DISPLAY_DEPS_ROOT:-$ROOT/.build/mas-display-deps}"
DOWNLOAD_ROOT="$DEPS_ROOT/downloads"
SOURCE_ARCHIVE="$DOWNLOAD_ROOT/ffmpeg-${VERSION}.tar.xz"
SOURCE_ROOT="$DEPS_ROOT/source"
BUILD_ROOT="$DEPS_ROOT/build"
PREFIX="$DEPS_ROOT/prefix"
CONFIGURE_PREFIX="/DroidLume/FFmpeg"
INSTALL_ROOT="$DEPS_ROOT/install-root"
METADATA="$DEPS_ROOT/build-metadata.env"
LICENSE_ROOT="$PREFIX/share/licenses/ffmpeg"

require_command() {
  if ! command -v "$1" >/dev/null 2>&1; then
    echo "required FFmpeg build tool not found: $1" >&2
    exit 69
  fi
}

verified_download() {
  local actual_sha256
  local temporary

  if [[ -f "$SOURCE_ARCHIVE" ]]; then
    actual_sha256="$(shasum -a 256 "$SOURCE_ARCHIVE" | awk '{print $1}')"
    if [[ "$actual_sha256" == "$SOURCE_SHA256" ]]; then
      echo "Using verified FFmpeg ${VERSION} source: $SOURCE_ARCHIVE"
      return
    fi
    echo "Discarding FFmpeg source with an unexpected SHA-256" >&2
    rm -f "$SOURCE_ARCHIVE"
  fi

  temporary="$(mktemp "${SOURCE_ARCHIVE}.download.XXXXXX")"
  echo "Downloading FFmpeg ${VERSION} from ffmpeg.org"
  if ! curl --fail --location --silent --show-error \
      "$SOURCE_URL" --output "$temporary"; then
    rm -f "$temporary"
    echo "failed to download FFmpeg from $SOURCE_URL" >&2
    exit 69
  fi

  actual_sha256="$(shasum -a 256 "$temporary" | awk '{print $1}')"
  if [[ "$actual_sha256" != "$SOURCE_SHA256" ]]; then
    rm -f "$temporary"
    echo "FFmpeg source SHA-256 mismatch" >&2
    echo "expected: $SOURCE_SHA256" >&2
    echo "actual:   $actual_sha256" >&2
    exit 65
  fi
  mv "$temporary" "$SOURCE_ARCHIVE"
}

for tool in curl shasum awk mktemp tar make xcrun otool pkg-config; do
  require_command "$tool"
done

ARCH="${DROIDLUME_FFMPEG_ARCH:-$(uname -m)}"
case "$ARCH" in
  arm64|x86_64) ;;
  *)
    echo "unsupported macOS FFmpeg architecture: $ARCH" >&2
    exit 64
    ;;
esac

if [[ "$ARCH" != "$(uname -m)" ]]; then
  echo "run this script natively on the requested architecture: $ARCH" >&2
  exit 64
fi

MACOS_SDK="$(xcrun --sdk macosx --show-sdk-path)"
[[ -d "$MACOS_SDK" ]] || {
  echo "active macOS SDK is missing: $MACOS_SDK" >&2
  exit 69
}

CPU_COUNT="$(sysctl -n hw.logicalcpu 2>/dev/null || echo 4)"
DEFAULT_JOBS="$CPU_COUNT"
(( DEFAULT_JOBS > 8 )) && DEFAULT_JOBS=8
JOBS="${DROIDLUME_FFMPEG_JOBS:-$DEFAULT_JOBS}"

typeset -a CONFIGURE_OPTIONS
CONFIGURE_OPTIONS=(
  "--prefix=$CONFIGURE_PREFIX"
  "--arch=$ARCH"
  --target-os=darwin
  "--sysroot=$MACOS_SDK"
  "--cc=$(xcrun --find clang)"
  "--cxx=$(xcrun --find clang++)"
  "--ar=$(xcrun --find ar)"
  "--strip=$(xcrun --find strip)"
  "--host-cc=$(xcrun --find clang)"
  "--host-ld=$(xcrun --find clang)"
  "--host-cflags=-isysroot $MACOS_SDK"
  "--host-ldflags=-isysroot $MACOS_SDK"
  --install-name-dir=@rpath
  --enable-shared
  --disable-static
  --disable-doc
  --disable-debug
  --disable-stripping
  --disable-gpl
  --disable-version3
  --disable-nonfree
  --disable-autodetect
  --disable-network
  --disable-everything
  --disable-avdevice
  --enable-avfilter
  --disable-swscale
  --disable-ffplay
  --disable-ffprobe
  --enable-ffmpeg
  --enable-avcodec
  --enable-avformat
  --enable-avutil
  --enable-swresample
  --enable-zlib
  --disable-libx264
  --disable-libx265
  --disable-libdav1d
  --disable-libopus
  --disable-libsvtav1
  --disable-libvpx
  --disable-openssl
  --enable-decoder=h264
  --enable-decoder=hevc
  --enable-decoder=av1
  --enable-decoder=vp8
  --enable-decoder=vp9
  --enable-decoder=opus
  --enable-decoder=aac
  --enable-decoder=flac
  --enable-decoder=pcm_s16le
  --enable-decoder=png
  --enable-parser=h264
  --enable-parser=hevc
  --enable-parser=av1
  --enable-parser=vp8
  --enable-parser=vp9
  --enable-parser=opus
  --enable-parser=aac
  --enable-parser=flac
  --enable-parser=png
  --enable-demuxer=image2
  --enable-demuxer=image2pipe
  --enable-demuxer=image_png_pipe
  --enable-muxer=mp4
  --enable-muxer=mov
  --enable-muxer=matroska
  --enable-muxer=webm
  --enable-muxer=opus
  --enable-muxer=flac
  --enable-muxer=wav
  --enable-protocol=file
  --enable-protocol=pipe
  --enable-bsf=aac_adtstoasc
  --enable-bsf=extract_extradata
  --enable-bsf=h264_mp4toannexb
  --enable-bsf=hevc_mp4toannexb
  --enable-bsf=av1_frame_merge
  --enable-bsf=vp9_superframe
  --extra-cflags=-mmacosx-version-min=14.0
  --extra-ldflags=-mmacosx-version-min=14.0
)

CONFIG_SHA256="$(printf '%s\n' "${CONFIGURE_OPTIONS[@]}" | shasum -a 256 | awk '{print $1}')"

mkdir -p "$DOWNLOAD_ROOT"
verified_download

if [[ "${DROIDLUME_FFMPEG_REBUILD:-0}" != "1" \
      && -f "$METADATA" \
      && -x "$PREFIX/bin/ffmpeg" ]]; then
  STORED_VERSION="$(awk -F= '$1 == "version" {print $2}' "$METADATA")"
  STORED_SOURCE_SHA="$(awk -F= '$1 == "source_sha256" {print $2}' "$METADATA")"
  STORED_CONFIG_SHA="$(awk -F= '$1 == "config_sha256" {print $2}' "$METADATA")"
  STORED_ARCH="$(awk -F= '$1 == "arch" {print $2}' "$METADATA")"
  if [[ "$STORED_VERSION" == "$VERSION" \
        && "$STORED_SOURCE_SHA" == "$SOURCE_SHA256" \
        && "$STORED_CONFIG_SHA" == "$CONFIG_SHA256" \
        && "$STORED_ARCH" == "$ARCH" ]]; then
    if DROIDLUME_MAS_DISPLAY_DEPS_ROOT="$DEPS_ROOT" \
        "$ROOT/scripts/verify-mas-ffmpeg.sh" >/dev/null; then
      rm -rf "$PREFIX/share/ffmpeg"
      "$ROOT/scripts/package-mas-ffmpeg-source.sh" >/dev/null
      echo "Using verified cached LGPL FFmpeg: $PREFIX"
      exit 0
    fi
    echo "Cached FFmpeg failed verification; rebuilding" >&2
  fi
fi

rm -rf "$SOURCE_ROOT" "$BUILD_ROOT" "$PREFIX" "$INSTALL_ROOT"
mkdir -p "$SOURCE_ROOT" "$BUILD_ROOT" "$PREFIX"
tar -xJf "$SOURCE_ARCHIVE" --strip-components=1 -C "$SOURCE_ROOT"
ln -s "$SOURCE_ROOT" "$BUILD_ROOT/src"

echo "Configuring isolated LGPL-only FFmpeg ${VERSION} ($ARCH)"
(
  cd "$BUILD_ROOT"
  ./src/configure "${CONFIGURE_OPTIONS[@]}"
)

echo "Compiling FFmpeg with $JOBS jobs"
make -C "$BUILD_ROOT" -j"$JOBS"
make -C "$BUILD_ROOT" install DESTDIR="$INSTALL_ROOT"

rm -rf "$PREFIX"
mv "$INSTALL_ROOT$CONFIGURE_PREFIX" "$PREFIX"
rm -rf "$INSTALL_ROOT"

for pc_file in "$PREFIX"/lib/pkgconfig/*.pc; do
  sed -i '' "s|^prefix=.*$|prefix=$PREFIX|" "$pc_file"
done

# The upstream install target ships encoder-oriented example presets even when
# their matching external libraries are disabled. They are not used by the
# display engine and are omitted to keep the isolated runtime unambiguous.
rm -rf "$PREFIX/share/ffmpeg"

mkdir -p "$LICENSE_ROOT"
cp "$SOURCE_ROOT/LICENSE.md" "$LICENSE_ROOT/FFmpeg-LICENSE.md"
cp "$SOURCE_ROOT/COPYING.LGPLv2.1" "$LICENSE_ROOT/COPYING.LGPLv2.1.txt"

cat > "$METADATA" <<EOF
version=$VERSION
source_url=$SOURCE_URL
source_sha256=$SOURCE_SHA256
config_sha256=$CONFIG_SHA256
arch=$ARCH
minimum_macos=14.0
license=LGPL-2.1-or-later
EOF

DROIDLUME_MAS_DISPLAY_DEPS_ROOT="$DEPS_ROOT" \
  "$ROOT/scripts/verify-mas-ffmpeg.sh"

"$ROOT/scripts/package-mas-ffmpeg-source.sh"

echo "Built isolated FFmpeg: $PREFIX"
