#!/usr/bin/env bash
set -euo pipefail

# Reproducible custom WebRTC AAR build for Rosetta Android.
# Requirements:
#   - Linux machine
#   - depot_tools in PATH
#   - python3, git

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROSETTA_ANDROID_DIR="$(cd "${SCRIPT_DIR}/../.." && pwd)"
PATCH_FILES=(
  "${SCRIPT_DIR}/patches/0001-audio-e2ee-pass-rtp-timestamp-as-additional-data.patch"
  "${SCRIPT_DIR}/patches/0002-android-build-on-mac-host.patch"
  "${SCRIPT_DIR}/patches/0003-macos-host-java-ijar.patch"
  "${SCRIPT_DIR}/patches/0004-macos-linker-missing-L-dirs.patch"
  "${SCRIPT_DIR}/patches/0005-macos-server-utils-socket.patch"
)

# Default target: WebRTC M125 family used by app dependency 125.6422.07.
WEBRTC_BRANCH="${WEBRTC_BRANCH:-branch-heads/6422}"
WEBRTC_TAG="${WEBRTC_TAG:-}"

# Source checkout root (contains src/)
WEBRTC_ROOT="${WEBRTC_ROOT:-$HOME/webrtc_android}"
WEBRTC_SRC="${WEBRTC_SRC:-${WEBRTC_ROOT}/src}"

# Output AAR consumed by app/build.gradle.kts.
OUT_AAR="${OUT_AAR:-${ROSETTA_ANDROID_DIR}/app/libs/libwebrtc-custom.aar}"

# Sync tuning to survive chromium.googlesource short-term 429 limits.
SYNC_JOBS="${SYNC_JOBS:-1}"
SYNC_RETRIES="${SYNC_RETRIES:-8}"
SYNC_RETRY_BASE_SEC="${SYNC_RETRY_BASE_SEC:-20}"

# Architectures used by the app.
ARCHS=("armeabi-v7a" "arm64-v8a" "x86_64")

echo "[webrtc-custom] root: ${WEBRTC_ROOT}"
echo "[webrtc-custom] src:  ${WEBRTC_SRC}"
echo "[webrtc-custom] out:  ${OUT_AAR}"
echo "[webrtc-custom] sync jobs: ${SYNC_JOBS}, retries: ${SYNC_RETRIES}"

# Keep depot_tools from auto-updating during long runs.
export DEPOT_TOOLS_UPDATE=0

retry_cmd() {
  local max_attempts="$1"
  shift
  local attempt=1
  local backoff="${SYNC_RETRY_BASE_SEC}"

  while true; do
    if "$@"; then
      return 0
    fi
    if (( attempt >= max_attempts )); then
      return 1
    fi
    echo "[webrtc-custom] attempt ${attempt}/${max_attempts} failed, retrying in ${backoff}s: $*"
    sleep "${backoff}"
    backoff=$(( backoff * 2 ))
    if (( backoff > 300 )); then
      backoff=300
    fi
    attempt=$(( attempt + 1 ))
  done
}

sync_with_retry() {
  local attempt=1
  while true; do
    # Heal known broken checkout state after interrupted/failed gclient runs.
    if [[ -d "${WEBRTC_SRC}/third_party/libjpeg_turbo/.git" ]]; then
      git -C "${WEBRTC_SRC}/third_party/libjpeg_turbo" reset --hard >/dev/null 2>&1 || true
      git -C "${WEBRTC_SRC}/third_party/libjpeg_turbo" clean -fd >/dev/null 2>&1 || true
    fi
    if [[ -d "${WEBRTC_ROOT}/_bad_scm/src/third_party" ]]; then
      find "${WEBRTC_ROOT}/_bad_scm/src/third_party" -maxdepth 1 -type d -name 'libjpeg_turbo*' -exec rm -rf {} + >/dev/null 2>&1 || true
    fi

    if gclient sync -D --jobs "${SYNC_JOBS}"; then
      return 0
    fi

    if (( attempt >= SYNC_RETRIES )); then
      echo "[webrtc-custom] ERROR: gclient sync failed after ${SYNC_RETRIES} attempts"
      echo "[webrtc-custom] Tip: wait 10-15 min and rerun with lower burst:"
      echo "[webrtc-custom]      SYNC_JOBS=1 SYNC_RETRIES=12 ./build_custom_webrtc.sh"
      return 1
    fi

    local wait_sec=$(( SYNC_RETRY_BASE_SEC * attempt ))
    if (( wait_sec > 300 )); then
      wait_sec=300
    fi
    echo "[webrtc-custom] gclient sync failed (attempt ${attempt}/${SYNC_RETRIES}), sleeping ${wait_sec}s..."
    sleep "${wait_sec}"
    attempt=$(( attempt + 1 ))
  done
}

if ! command -v fetch >/dev/null 2>&1; then
  echo "[webrtc-custom] ERROR: depot_tools 'fetch' not found in PATH"
  exit 1
fi

if [[ ! -d "${WEBRTC_SRC}/.git" ]]; then
  echo "[webrtc-custom] checkout not found, fetching webrtc_android..."
  mkdir -p "${WEBRTC_ROOT}"
  pushd "${WEBRTC_ROOT}" >/dev/null
  retry_cmd "${SYNC_RETRIES}" fetch --nohooks --no-history webrtc_android
  sync_with_retry
  popd >/dev/null
fi

pushd "${WEBRTC_SRC}" >/dev/null

echo "[webrtc-custom] syncing source..."
retry_cmd "${SYNC_RETRIES}" git fetch --all --tags

if [[ -n "${WEBRTC_TAG}" ]]; then
  retry_cmd "${SYNC_RETRIES}" git checkout "${WEBRTC_TAG}"
else
  if git show-ref --verify --quiet "refs/remotes/origin/${WEBRTC_BRANCH}"; then
    retry_cmd "${SYNC_RETRIES}" git checkout -B "${WEBRTC_BRANCH}" "origin/${WEBRTC_BRANCH}"
  else
    retry_cmd "${SYNC_RETRIES}" git checkout "${WEBRTC_BRANCH}"
  fi
  if git rev-parse --abbrev-ref --symbolic-full-name '@{u}' >/dev/null 2>&1; then
    retry_cmd "${SYNC_RETRIES}" git pull --ff-only
  else
    echo "[webrtc-custom] no upstream for current branch, skipping git pull"
  fi
fi

sync_with_retry

echo "[webrtc-custom] applying Rosetta patch..."
git reset --hard
for patch in "${PATCH_FILES[@]}"; do
  echo "[webrtc-custom] apply $(basename "${patch}")"
  git apply --check "${patch}"
  git apply "${patch}"
done

# macOS host tweaks:
# - point third_party/jdk/current to local JDK
# - use locally installed Android NDK (darwin toolchain)
if [[ "$(uname -s)" == "Darwin" ]]; then
  if [[ -z "${JAVA_HOME:-}" ]]; then
    JAVA_HOME="$(/usr/libexec/java_home 2>/dev/null || true)"
  fi
  if [[ -z "${JAVA_HOME:-}" || ! -d "${JAVA_HOME}" ]]; then
    echo "[webrtc-custom] ERROR: JAVA_HOME not found on macOS"
    exit 1
  fi
  JAVA_HOME_CANDIDATE="${JAVA_HOME}"
  if [[ ! -f "${JAVA_HOME_CANDIDATE}/conf/logging.properties" ]] && [[ -d "${JAVA_HOME_CANDIDATE}/libexec/openjdk.jdk/Contents/Home" ]]; then
    JAVA_HOME_CANDIDATE="${JAVA_HOME_CANDIDATE}/libexec/openjdk.jdk/Contents/Home"
  fi
  if [[ ! -f "${JAVA_HOME_CANDIDATE}/conf/logging.properties" ]]; then
    echo "[webrtc-custom] ERROR: invalid JAVA_HOME (conf/logging.properties not found): ${JAVA_HOME}"
    exit 1
  fi
  JAVA_HOME="${JAVA_HOME_CANDIDATE}"
  ln -sfn "${JAVA_HOME}" "${WEBRTC_SRC}/third_party/jdk/current"
  echo "[webrtc-custom] macOS JDK linked: ${WEBRTC_SRC}/third_party/jdk/current -> ${JAVA_HOME}"
fi

mkdir -p "$(dirname "${OUT_AAR}")"

echo "[webrtc-custom] building AAR (this can take a while)..."
GN_ARGS=(
  is_debug=false
  is_component_build=false
  rtc_include_tests=false
  rtc_build_examples=false
)

if [[ "$(uname -s)" == "Darwin" ]]; then
  MAC_ANDROID_NDK_ROOT="${MAC_ANDROID_NDK_ROOT:-$HOME/Library/Android/sdk/ndk/27.1.12297006}"
  if [[ ! -d "${MAC_ANDROID_NDK_ROOT}" ]]; then
    echo "[webrtc-custom] ERROR: Android NDK not found at ${MAC_ANDROID_NDK_ROOT}"
    echo "[webrtc-custom] Set MAC_ANDROID_NDK_ROOT to your local NDK path."
    exit 1
  fi
  GN_ARGS+=("android_ndk_root=\"${MAC_ANDROID_NDK_ROOT}\"")
  GN_ARGS+=("android_ndk_version=\"27.1.12297006\"")
  echo "[webrtc-custom] macOS Android NDK: ${MAC_ANDROID_NDK_ROOT}"
fi

python3 tools_webrtc/android/build_aar.py \
  --build-dir out_rosetta_aar \
  --output "${OUT_AAR}" \
  --arch "${ARCHS[@]}" \
  --extra-gn-args "${GN_ARGS[@]}"

echo "[webrtc-custom] done"
echo "[webrtc-custom] AAR: ${OUT_AAR}"

popd >/dev/null
