#!/usr/bin/env bash
#
# Builds libmpv for Android under the LGPL (instead of the GPL build in app/libs/libmpv-0.4.1.aar).
#
# Starting point: https://github.com/jarnedemeulemeester/libmpv-android (branch main by default, MIT scripts;
# set UPSTREAM_TAG to a tag such as v0.4.1 or v1.0.0, or to a commit-pinned branch, to build another version).
# Three changes are made to its build scripts:
#   1. mpv:    meson option -Dgpl=false           (mpv stays LGPL-2.1+)
#   2. FFmpeg: --enable-{gpl,version3} becomes --enable-version3   (no GPL parts; mbedTLS needs version3)
#   3. FFmpeg: libpostproc is no longer linked    (it only exists in GPL builds)
#
# Result, in ./out :
#   libmpv-<mpv version>-lgpl.aar            -> goes in app/libs/
#   jellywatch-libmpv-source-<date>.tar.gz   -> source of the LGPL parts, scripts and changes (to publish)
#   lgpl-changes.diff                        -> the changes made to the upstream scripts
#   LIBMPV_BUILD.txt                         -> versions, checks, checksums
#
# Needs: Linux (Debian/Ubuntu: the upstream script installs the packages itself, so run as root or
# with sudo available), git, about 10 GB of disk, a good internet link. Takes 1 to 2 hours.
#
set -euo pipefail

UPSTREAM_URL="https://github.com/jarnedemeulemeester/libmpv-android.git"
UPSTREAM_TAG="${UPSTREAM_TAG:-main}"

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# No ":" or space in this path: the Android build tools fail with them.
WORK="${LIBMPV_WORK_DIR:-${HOME}/jellywatch-libmpv-work}"
case "$WORK" in *[:\ ]*) echo "ERROR: LIBMPV_WORK_DIR must not contain ':' or a space" >&2; exit 1 ;; esac
SRC="${WORK}/libmpv-android"
OUT="${HERE}/out"

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

[[ "$(uname -s)" == "Linux" ]] || die "Linux only"
command -v git >/dev/null 2>&1 || die "'git' is missing"
mkdir -p "$WORK" "$OUT"

# ── 1. Upstream scripts ──────────────────────────────────────────────────────
step "Getting libmpv-android ${UPSTREAM_TAG}"
if [[ ! -d "${SRC}/.git" ]]; then
  git clone --branch "$UPSTREAM_TAG" --depth 1 "$UPSTREAM_URL" "$SRC"
fi
UPSTREAM_COMMIT="$(git -C "$SRC" rev-parse HEAD)"

# ── 2. LGPL changes ──────────────────────────────────────────────────────────
step "Applying the LGPL changes"
cd "$SRC"
git checkout --quiet -- buildscripts/scripts/ffmpeg.sh buildscripts/scripts/mpv.sh

FFMPEG_SH="buildscripts/scripts/ffmpeg.sh"
MPV_SH="buildscripts/scripts/mpv.sh"

grep -q -- '--enable-{gpl,version3}' "$FFMPEG_SH" || die "ffmpeg.sh is not the expected version (no --enable-{gpl,version3})"
sed -i 's/--enable-{gpl,version3}/--enable-version3/' "$FFMPEG_SH"
sed -i '/libpostproc\.so/d' "$FFMPEG_SH"

grep -q -- '-Dmanpage-build=disabled' "$MPV_SH" || die "mpv.sh is not the expected version"
sed -i 's/^\t-Dmanpage-build=disabled$/\t-Dmanpage-build=disabled \\\n\t-Dgpl=false/' "$MPV_SH"

# The changes must be there, and the GPL switches must be gone.
grep -q -- '--enable-version3' "$FFMPEG_SH"        || die "ffmpeg.sh change failed"
! grep -q -- 'enable-{gpl' "$FFMPEG_SH"            || die "ffmpeg.sh still enables the GPL"
! grep -q -- 'libpostproc' "$FFMPEG_SH"            || die "ffmpeg.sh still links libpostproc"
grep -q -- '-Dgpl=false' "$MPV_SH"                 || die "mpv.sh change failed"

git diff > "${OUT}/lgpl-changes.diff"
echo "Changes saved in ${OUT}/lgpl-changes.diff"

# ── 3. Dependencies (Android SDK + NDK, sources, system packages) ────────────
step "Downloading the Android SDK/NDK and the sources (upstream download.sh)"
cd "${SRC}/buildscripts"
./download.sh
[[ -x ./patch.sh ]] && ./patch.sh

# ── 4. Build ─────────────────────────────────────────────────────────────────
step "Building for armeabi-v7a, arm64-v8a, x86, x86_64 (1 to 2 hours)"
./build.sh

AAR_SRC="$(find "${SRC}/libmpv/build/outputs/aar" -type f -name '*release*.aar' 2>/dev/null | head -1 || true)"
[[ -n "$AAR_SRC" ]] || die "No release AAR found in libmpv/build/outputs/aar"
MPV_VERSION="$(sed -n 's/^v_mpv=//p' "${SRC}/buildscripts/include/depinfo.sh" | head -1)"
AAR_OUT="${OUT}/libmpv-${MPV_VERSION}-lgpl.aar"
cp "$AAR_SRC" "$AAR_OUT"

# ── 5. Checks on the result ──────────────────────────────────────────────────
step "Checking the license of the result"
CHECK="$(mktemp -d)"
trap 'rm -rf "$CHECK"' EXIT
unzip -q -o "$AAR_OUT" 'jni/arm64-v8a/*' -d "$CHECK"
LIB="${CHECK}/jni/arm64-v8a"

[[ ! -e "${LIB}/libpostproc.so" ]] || die "libpostproc.so is in the AAR: it is a GPL-only library"
for f in libavutil.so libavcodec.so libmpv.so; do
  [[ -f "${LIB}/${f}" ]] || die "${f} missing in the AAR"
done

AVUTIL_LICENSE="$(strings -n 6 "${LIB}/libavutil.so" | grep -m1 'libavutil license:' || true)"
echo "FFmpeg says: ${AVUTIL_LICENSE:-<no license string found>}"
[[ "$AVUTIL_LICENSE" == *LGPL* ]] || die "FFmpeg is not reported as LGPL: ${AVUTIL_LICENSE:-no license string}"

MPV_FEATURES="$(strings -n 6 "${LIB}/libmpv.so" | grep -m1 'List of enabled features' || true)"
echo "mpv says: ${MPV_FEATURES:-<no feature list found>}"
if [[ " $MPV_FEATURES " == *" gpl "* ]]; then die "mpv still lists the 'gpl' feature"; fi

# ── 6. Source to publish (LGPL parts) ────────────────────────────────────────
step "Packing the source of the LGPL parts"
DATE="$(date -u +%Y%m%d)"
SOURCE_TAR="${OUT}/jellywatch-libmpv-source-${DATE}.tar.gz"
DEPS="${SRC}/buildscripts/deps"
TAR_PATHS=(buildscripts/scripts buildscripts/include libmpv/src)
for f in buildscripts/*.sh buildscripts/patches; do
  [[ -e "${SRC}/${f}" ]] && TAR_PATHS+=("$f")
done
for dep in ffmpeg mpv libplacebo fribidi; do
  if [[ -d "${DEPS}/${dep}" ]]; then
    TAR_PATHS+=("buildscripts/deps/${dep}")
  else
    echo "WARNING: ${DEPS}/${dep} not found" >&2
  fi
done
( cd "$SRC" && tar --exclude='.git' --exclude='_build*' --exclude='__pycache__' --exclude='*.pyc' -czf "$SOURCE_TAR" "${TAR_PATHS[@]}" )
cp "${OUT}/lgpl-changes.diff" "${OUT}/lgpl-changes-${DATE}.diff"

# ── 7. Report ────────────────────────────────────────────────────────────────
step "Writing LIBMPV_BUILD.txt"
SHA256="sha256sum"; command -v sha256sum >/dev/null 2>&1 || SHA256="shasum -a 256"
{
  echo "JellyWatch - libmpv (LGPL) build"
  echo "Date (UTC)   : $(date -u +%Y-%m-%dT%H:%M:%SZ)"
  echo
  echo "Upstream     : ${UPSTREAM_URL}"
  echo "Tag / commit : ${UPSTREAM_TAG} / ${UPSTREAM_COMMIT}  (scripts under MIT)"
  echo "Changes      : lgpl-changes.diff"
  echo "                 mpv    -Dgpl=false"
  echo "                 FFmpeg --enable-version3 only (no --enable-gpl), libpostproc not linked"
  echo
  echo "Dependency versions (buildscripts/include/depinfo.sh):"
  grep -E '^v_(lua|libass|libunibreak|harfbuzz|fribidi|freetype|libxml2|fontconfig|mbedtls|curl|libplacebo|dav1d|ffmpeg|mpv)=' "${SRC}/buildscripts/include/depinfo.sh" | sed 's/^/  /'
  echo
  echo "Check        : ${AVUTIL_LICENSE}"
  echo "               ${MPV_FEATURES}"
  echo "               libpostproc.so: absent"
  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 libmpv, FFmpeg and libplacebo under the LGPL."
  echo "The source code can be downloaded from: <URL of $(basename "$SOURCE_TAR")>"
} > "${OUT}/LIBMPV_BUILD.txt"

step "Done"
echo "AAR     : ${AAR_OUT}"
echo "Source  : ${SOURCE_TAR}"
echo "Report  : ${OUT}/LIBMPV_BUILD.txt"
echo
echo "Next: test playback with the AAR, then copy it to app/libs/ and point app/build.gradle.kts to it."
