#!/usr/bin/env bash
# Met à jour les plugins WordPress.org dans www/wp-content/plugins/
# (ignore les plugins premium / custom introuvables sur l'API)

set -eo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
echo "Mise à jour des plugins WordPress.org dans ${ROOT}/www/wp-content/plugins/"
PLUGINS_DIR="${ROOT}/www/wp-content/plugins"
TMP_DIR="$(mktemp -d)"
trap 'rm -rf "$TMP_DIR"' EXIT

SKIP_REGEX='^(woocommerce copie|amlicencemanager|amaddons)$'

updated=()
skipped=()
failed=()

api_info() {
  local slug="$1"
  curl -fsS --max-time 30 \
    "https://api.wordpress.org/plugins/info/1.2/?action=plugin_information&request%5Bslug%5D=${slug}&request%5Bfields%5D%5Bversions%5D=0&request%5Bfields%5D%5Bactive_installs%5D=0" \
    2>/dev/null || true
}

for dir in "$PLUGINS_DIR"/*/; do
  name="$(basename "$dir")"
  if [[ "$name" =~ $SKIP_REGEX ]]; then
    skipped+=("$name (exclu)")
    continue
  fi

  slug="$name"
  json="$(api_info "$slug")"
  if [[ -z "$json" ]] || ! echo "$json" | grep -q '"download_link"'; then
    skipped+=("$name (hors WordPress.org)")
    continue
  fi

  version="$(echo "$json" | python3 -c "import sys,json; print(json.load(sys.stdin).get('version',''))" 2>/dev/null || true)"
  download="$(echo "$json" | python3 -c "import sys,json; print(json.load(sys.stdin).get('download_link',''))" 2>/dev/null || true)"
  if [[ -z "$version" || -z "$download" ]]; then
    failed+=("$name (réponse API invalide)")
    continue
  fi

  main_php="${dir}${slug}.php"
  if [[ ! -f "$main_php" ]]; then
    main_php="$(find "$dir" -maxdepth 1 -name '*.php' | head -1)"
  fi
  current=""
  if [[ -f "$main_php" ]]; then
    current="$(grep -m1 'Version:' "$main_php" 2>/dev/null | sed 's/.*Version: *//' | tr -d '\r' | xargs || true)"
  fi

  if [[ "$current" == "$version" ]]; then
    skipped+=("$name (déjà en ${version})")
    continue
  fi

  echo "→ ${name}: ${current:-?} → ${version}"
  zip="${TMP_DIR}/${slug}.zip"
  curl -fsSL --max-time 120 "$download" -o "$zip"
  extract="${TMP_DIR}/extract"
  rm -rf "$extract"
  mkdir -p "$extract"
  unzip -oq "$zip" -d "$extract"
  src="${extract}/${slug}"
  if [[ ! -d "$src" ]]; then
    failed+=("$name (archive invalide)")
    continue
  fi
  rm -rf "$dir"
  mv "$src" "$dir"
  updated+=("$name ${current:-?}→${version}")
done

echo ""
echo "=== Mis à jour (${#updated[@]}) ==="
if ((${#updated[@]})); then printf '%s\n' "${updated[@]}"; fi

echo ""
echo "=== Ignorés (${#skipped[@]}) ==="
if ((${#skipped[@]})); then printf '%s\n' "${skipped[@]}"; fi

if ((${#failed[@]})); then
  echo ""
  echo "=== Échecs (${#failed[@]}) ==="
  printf '%s\n' "${failed[@]}"
  exit 1
fi
