#!/usr/bin/env bash
#
# Builds the FFmpeg audio decoder for ExoPlayer (AndroidX Media3) used by JellyWatch.
#
# Result, in ./out :
#   media3-decoder-ffmpeg-<media3 tag>.aar   -> copy it to app/libs/
#   ffmpeg-<commit>-source.tar.gz            -> FFmpeg source to publish (LGPL)
#   FFMPEG_BUILD.txt                         -> versions, configure options, checksums
#
# The AndroidX module is Apache-2.0. FFmpeg is built without --enable-gpl and
# --enable-nonfree, so it stays under the LGPL-2.1+.
#
# Needs: Linux or macOS (on Windows: WSL2), git, JDK 17+, Android SDK (ANDROID_HOME),
# NDK r26b, CMake 3.21+. See README.md.
#
set -euo pipefail

# ── Settings (override with environment variables) ───────────────────────────
MEDIA3_TAG="${MEDIA3_TAG:-1.11.1}"                  # same as `media3` in gradle/libs.versions.toml
FFMPEG_BRANCH="${FFMPEG_BRANCH:-n9.0.2}"            # a tag or a branch. AndroidX recommends release/6.0; 9.0.2 is the latest release
FFMPEG_COMMIT="${FFMPEG_COMMIT:-}"                  # optional: pin an exact commit (reproducible build)
ANDROID_ABI="${ANDROID_ABI:-23}"                    # = minSdk of the app, must not exceed it
NDK_VERSION="${NDK_VERSION:-26.1.10909125}"         # NDK r26b
DECODERS="${DECODERS:-flac alac pcm_mulaw pcm_alaw mp3 aac ac3 eac3 dca mlp truehd}"

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# The work folder must have no ":" or space in its path: Gradle's wrapper fails with them
# (the project folder is called "JellyWatch: for Android TV").
WORK="${FFMPEG_WORK_DIR:-${HOME}/jellywatch-ffmpeg-work}"
case "$WORK" in *[:\ ]*) echo "ERROR: FFMPEG_WORK_DIR must not contain ':' or a space" >&2; exit 1 ;; esac
OUT="${HERE}/out"
MEDIA_DIR="${WORK}/media"
JNI_DIR="${MEDIA_DIR}/libraries/decoder_ffmpeg/src/main/jni"
FFMPEG_DIR="${JNI_DIR}/ffmpeg"

die() { echo "ERROR: $*" >&2; exit 1; }
step() { echo; echo "==> $*"; }

# ── Checks ───────────────────────────────────────────────────────────────────
step "Checking the environment"
for tool in git java tar unzip; do
  command -v "$tool" >/dev/null 2>&1 || die "'$tool' is missing"
done
command -v sha256sum >/dev/null 2>&1 && SHA256="sha256sum" || SHA256="shasum -a 256"

SDK_ROOT="${ANDROID_HOME:-${ANDROID_SDK_ROOT:-}}"
[[ -n "$SDK_ROOT" ]] || die "Set ANDROID_HOME to the Android SDK folder"

NDK_PATH="${ANDROID_NDK_HOME:-${SDK_ROOT}/ndk/${NDK_VERSION}}"
if [[ ! -d "$NDK_PATH" ]]; then
  die "NDK not found at $NDK_PATH. Install it with:
  \"${SDK_ROOT}/cmdline-tools/latest/bin/sdkmanager\" \"ndk;${NDK_VERSION}\" \"cmake;3.31.1\""
fi

case "$(uname -s)" in
  Linux)  HOST_PLATFORM="linux-x86_64" ;;
  Darwin) HOST_PLATFORM="darwin-x86_64" ;;
  *)      die "Unsupported system $(uname -s). On Windows use WSL2." ;;
esac

export ANDROID_HOME="$SDK_ROOT"
mkdir -p "$WORK" "$OUT"

# ── 1. AndroidX Media3 source, at the tag of the app ─────────────────────────
step "Getting AndroidX Media3 ${MEDIA3_TAG}"
if [[ ! -d "${MEDIA_DIR}/.git" ]]; then
  git clone --branch "$MEDIA3_TAG" --depth 1 https://github.com/androidx/media.git "$MEDIA_DIR"
fi
MEDIA3_COMMIT="$(git -C "$MEDIA_DIR" rev-parse HEAD)"

# ── 2. FFmpeg source ─────────────────────────────────────────────────────────
step "Getting FFmpeg (${FFMPEG_BRANCH}${FFMPEG_COMMIT:+ @ ${FFMPEG_COMMIT}})"
if [[ ! -d "${FFMPEG_DIR}/.git" ]]; then
  git clone --branch "$FFMPEG_BRANCH" --depth 1 https://git.ffmpeg.org/ffmpeg.git "$FFMPEG_DIR"
  if [[ -n "$FFMPEG_COMMIT" ]]; then
    git -C "$FFMPEG_DIR" fetch --depth 1 origin "$FFMPEG_COMMIT"
    git -C "$FFMPEG_DIR" checkout --quiet "$FFMPEG_COMMIT"
  fi
fi
FFMPEG_HEAD="$(git -C "$FFMPEG_DIR" rev-parse HEAD)"
FFMPEG_SHORT="$(git -C "$FFMPEG_DIR" rev-parse --short=10 HEAD)"

# Source for the LGPL obligation, taken before any build output is created.
SOURCE_TAR="${OUT}/ffmpeg-${FFMPEG_SHORT}-source.tar.gz"
git -C "$FFMPEG_DIR" archive --format=tar.gz --prefix="ffmpeg-${FFMPEG_SHORT}/" -o "$SOURCE_TAR" HEAD
git -C "$FFMPEG_DIR" diff > "${OUT}/ffmpeg-changes.diff"      # empty: FFmpeg is not modified

# FFmpeg 9 no longer contains libpostproc, so its configure rejects --disable-postproc.
# That is the only change made to the AndroidX build script; it is saved with the other outputs.
git -C "$MEDIA_DIR" checkout --quiet -- libraries/decoder_ffmpeg/src/main/jni/build_ffmpeg.sh
if [[ ! -d "${FFMPEG_DIR}/libpostproc" ]]; then
  sed -i '/--disable-postproc/d' "${JNI_DIR}/build_ffmpeg.sh"
fi
git -C "$MEDIA_DIR" diff -- libraries/decoder_ffmpeg/src/main/jni/build_ffmpeg.sh > "${OUT}/androidx-build-script-changes.diff"

# ── 3. Static license check of the build options ─────────────────────────────
step "Checking that the build options keep FFmpeg under the LGPL"
if grep -E -- "--enable-(gpl|nonfree|version3)" "${JNI_DIR}/build_ffmpeg.sh" >/dev/null; then
  die "build_ffmpeg.sh enables GPL, version3 or nonfree: the result would not be plain LGPL-2.1+"
fi

# ── 4. Build FFmpeg (static libraries for the 4 ABIs) ────────────────────────
step "Building FFmpeg for armeabi-v7a, arm64-v8a, x86, x86_64 (this takes a while)"
# shellcheck disable=SC2206
DECODER_LIST=($DECODERS)
( cd "$JNI_DIR" && ./build_ffmpeg.sh "${JNI_DIR%/jni}" "$NDK_PATH" "$HOST_PLATFORM" "$ANDROID_ABI" "${DECODER_LIST[@]}" )

# Check what the configure step really decided.
CONFIG_H="${FFMPEG_DIR}/config.h"
if [[ -f "$CONFIG_H" ]]; then
  for flag in CONFIG_GPL CONFIG_NONFREE CONFIG_VERSION3; do
    value="$(grep -E "^#define ${flag} " "$CONFIG_H" | awk '{print $3}' || true)"
    [[ "${value:-0}" == "0" ]] || die "${flag}=${value} in config.h: FFmpeg is not plain LGPL-2.1+"
  done
else
  echo "WARNING: ${CONFIG_H} not found, license flags not checked" >&2
fi

# ── 5. Build the AAR ─────────────────────────────────────────────────────────
step "Building the AAR with Gradle"
cd "$MEDIA_DIR"
MODULE="$(./gradlew -q --console=plain projects 2>/dev/null | grep -o "':[A-Za-z0-9_-]*ffmpeg[A-Za-z0-9_-]*'" | head -1 | tr -d "'" || true)"
MODULE="${MODULE:-:lib-decoder-ffmpeg}"
echo "Gradle module: ${MODULE}"
./gradlew --console=plain "${MODULE}:assembleRelease"

AAR_SRC="$(find "${MEDIA_DIR}/libraries/decoder_ffmpeg" -type f -name '*.aar' | grep -i release | head -1 || true)"
[[ -n "$AAR_SRC" ]] || die "No release AAR found under libraries/decoder_ffmpeg"

AAR_OUT="${OUT}/media3-decoder-ffmpeg-${MEDIA3_TAG}.aar"
cp "$AAR_SRC" "$AAR_OUT"

step "Checking the AAR content"
for abi in armeabi-v7a arm64-v8a x86 x86_64; do
  unzip -l "$AAR_OUT" | grep -q "jni/${abi}/libffmpegJNI.so" || die "libffmpegJNI.so missing for ${abi}"
done
unzip -l "$AAR_OUT" | grep -q "classes.jar" || die "classes.jar missing"

# ── 6. Build report (to keep with the published source) ──────────────────────
step "Writing FFMPEG_BUILD.txt"
CONFIGURE_OPTIONS="$(awk '/COMMON_OPTIONS="/{f=1} f{print} /^ *"$/{if(f)exit}' "${JNI_DIR}/build_ffmpeg.sh")"
{
  echo "JellyWatch - FFmpeg decoder build"
  echo "Date (UTC)        : $(date -u +%Y-%m-%dT%H:%M:%SZ)"
  echo
  echo "AndroidX Media3   : tag ${MEDIA3_TAG} (commit ${MEDIA3_COMMIT}), Apache-2.0"
  echo "FFmpeg            : branch ${FFMPEG_BRANCH}, commit ${FFMPEG_HEAD}"
  echo "FFmpeg license    : LGPL-2.1 or later (no --enable-gpl, no --enable-nonfree, no --enable-version3)"
  echo "FFmpeg changes    : none (see ffmpeg-changes.diff, empty)"
  echo "Android NDK       : ${NDK_VERSION}"
  echo "Android ABI level : ${ANDROID_ABI}"
  echo "Decoders          : ${DECODERS}"
  echo "Host              : ${HOST_PLATFORM}"
  echo
  echo "Common configure options (from build_ffmpeg.sh):"
  echo "${CONFIGURE_OPTIONS}"
  echo "Each decoder adds --enable-decoder=<name>."
  echo
  echo "Script            : tools/ffmpeg-decoder/build.sh"
  echo
  echo "Files:"
  ( cd "$OUT" && $SHA256 "$(basename "$AAR_OUT")" "$(basename "$SOURCE_TAR")" )
  echo
  echo "Notice for the app and the download page:"
  echo "This software uses libraries from the FFmpeg project under the LGPLv2.1."
  echo "The source code can be downloaded from: <URL of ffmpeg-${FFMPEG_SHORT}-source.tar.gz>"
} > "${OUT}/FFMPEG_BUILD.txt"

step "Done"
echo "AAR                : ${AAR_OUT}"
echo "FFmpeg source      : ${SOURCE_TAR}"
echo "Report             : ${OUT}/FFMPEG_BUILD.txt"
echo
echo "Next: copy the AAR to app/libs/ and point app/build.gradle.kts to it."
