#!/usr/bin/env bash
# Met à jour Advanced Custom Fields PRO via Composer (dépôt ACF).
#
# En production, la mise à jour automatique passe par une cron o2switch :
#   scripts/update-acf-pro-server.sh (install : scripts/setup-acf-pro-cron-server.sh)
#
# Prérequis :
#   - Composer installé (https://getcomposer.org/)
#   - .secrets/auth.json (voir .secrets/auth.json.example)
#     Doc : https://www.advancedcustomfields.com/resources/installing-acf-pro-with-composer/
#
# Usage local (depuis la racine du dépôt) :
#   ./scripts/update-acf-pro.sh
#   ./scripts/update-acf-pro.sh --check   # affiche la version sans modifier
#   ./scripts/update-acf-pro.sh --dry-run

set -euo pipefail

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

AUTH_FILE="${ACF_AUTH_FILE:-$ROOT/.secrets/auth.json}"
PACKAGE="wpengine/advanced-custom-fields-pro"
PLUGIN_PHP="$ROOT/www/wp-content/plugins/advanced-custom-fields-pro/acf.php"
DRY_RUN=false
CHECK_ONLY=false

usage() {
  sed -n '2,14p' "$0" | sed 's/^# \{0,1\}//'
  exit "${1:-0}"
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    -h|--help) usage 0 ;;
    --auth) AUTH_FILE="$2"; shift 2 ;;
    --dry-run) DRY_RUN=true; shift ;;
    --check) CHECK_ONLY=true; shift ;;
    *) echo "Option inconnue : $1" >&2; usage 1 ;;
  esac
done

if ! command -v composer >/dev/null 2>&1; then
  echo "Composer introuvable. Installez-le : https://getcomposer.org/" >&2
  exit 1
fi

if [[ ! -f "$AUTH_FILE" ]]; then
  echo "Fichier d’authentification introuvable : $AUTH_FILE" >&2
  echo "Copiez .secrets/auth.json.example vers .secrets/auth.json et renseignez la clé ACF PRO." >&2
  exit 1
fi

export COMPOSER_AUTH="$(cat "$AUTH_FILE")"

current_version() {
  if [[ -f "$PLUGIN_PHP" ]]; then
    grep -m1 'Version:' "$PLUGIN_PHP" | sed -E 's/.*Version:[[:space:]]*//; s/[[:space:]]*\*\/.*//; s/^[[:space:]]*//; s/[[:space:]]*$//'
  else
    echo "absent"
  fi
}

echo "ACF PRO actuel : $(current_version)"

if [[ "$CHECK_ONLY" == true ]]; then
  composer outdated "$PACKAGE" 2>/dev/null || true
  exit 0
fi

ARGS=(update "$PACKAGE" --no-interaction --with-all-dependencies)
[[ "$DRY_RUN" == true ]] && ARGS=(update "$PACKAGE" --dry-run --no-interaction)

echo "→ composer ${ARGS[*]}"
composer "${ARGS[@]}"

echo "ACF PRO après mise à jour : $(current_version)"
