#!/usr/bin/env bash
# Sync and initialize all third-party/ git submodules from .gitmodules (recursive nested).
# Used by rebuild.sh, ci-build.sh, and deploy paths — no network except submodule fetch/update.
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"

ONLY_PATH=""
while [[ $# -gt 0 ]]; do
  case "$1" in
    --only)
      ONLY_PATH="${2:-}"
      shift 2
      ;;
    -h|--help)
      echo "Usage: $0 [--only third-party/wireguard-android]"
      echo "  Initializes every path in .gitmodules under third-party/ (recursive)."
      exit 0
      ;;
    *)
      echo "error: unknown argument: $1" >&2
      exit 1
      ;;
  esac
done

if [[ ! -f .gitmodules ]]; then
  echo "error: .gitmodules not found in $ROOT" >&2
  exit 1
fi

mapfile -t SUB_PATHS < <(git config -f .gitmodules --get-regexp '^submodule\..*\.path$' \
  | awk '{ print $2 }' | grep '^third-party/' | sort -u)

if [[ ${#SUB_PATHS[@]} -eq 0 ]]; then
  echo "error: no third-party paths in .gitmodules" >&2
  exit 1
fi

if [[ -n "$ONLY_PATH" ]]; then
  SUB_PATHS=("$ONLY_PATH")
fi

ensure_gitlink() {
  local path="$1"
  local name="$path"
  if git cat-file -e "HEAD:${path}" 2>/dev/null \
     || git ls-files --stage "$path" | grep -q '^160000'; then
    return 0
  fi
  local url
  url="$(git config -f .gitmodules --get "submodule.${name}.url" || true)"
  if [[ -z "$url" ]]; then
    echo "error: $path listed in .gitmodules but no gitlink in tree and no url" >&2
    return 1
  fi
  local sha
  sha="$(git ls-remote "$url" HEAD | awk 'NR==1 {print $1}')"
  if [[ -z "$sha" ]]; then
    echo "error: could not resolve HEAD for $url (needed to register missing gitlink)" >&2
    return 1
  fi
  echo "WARN: registering missing gitlink for $path at $sha (commit this gitlink)" >&2
  git update-index --add --cacheinfo 160000,"$sha","$path"
}

validate_path() {
  local path="$1"
  case "$path" in
    third-party/wireguard-android)
      [[ -d "$path/tunnel/src/main/java" ]] \
        && [[ -f "$path/tunnel/tools/wireguard-tools/src/config.c" ]] \
        && [[ -f "$path/tunnel/tools/elf-cleaner/elf-cleaner.cpp" || -f "$path/tunnel/tools/elf-cleaner/main.cpp" ]]
      ;;
    third-party/libvpx)
      [[ -d "$path" ]]
      ;;
    third-party/opus|third-party/speex)
      [[ -f "$path/configure" || -f "$path/CMakeLists.txt" || -d "$path/include" ]]
      ;;
    *)
      [[ -d "$path" ]]
      ;;
  esac
}

echo "==> third-party submodules: sync + update --init --recursive"
for path in "${SUB_PATHS[@]}"; do
  if ! grep -q "$path" .gitmodules 2>/dev/null; then
    echo "error: $path not in .gitmodules" >&2
    exit 1
  fi
  ensure_gitlink "$path"
  git submodule sync "$path"
  git submodule update --init --recursive "$path"
  if ! validate_path "$path"; then
    echo "error: $path incomplete after submodule update (nested submodules missing?)" >&2
    exit 1
  fi
  short="$(git -C "$path" rev-parse --short HEAD 2>/dev/null || echo '?')"
  echo "    $path @ $short"
done

if [[ -d third-party/wireguard-android/tunnel ]]; then
  wg_tools="$(git -C third-party/wireguard-android/tunnel/tools/wireguard-tools rev-parse --short HEAD 2>/dev/null || echo '?')"
  echo "    third-party/wireguard-android/tunnel/tools/wireguard-tools @ $wg_tools"
fi

echo "==> third-party submodules ready"
