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

usage() {
  cat <<'TXT'
Uso:
  deploy-web-health-all.sh

Lee btec-core/clients/manifest.json y ejecuta deploy-web-health.sh en cada cliente enabled=true.
TXT
}

if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
  usage
  exit 0
fi

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
core_root="$(cd "$script_dir/.." && pwd)"
manifest="$core_root/clients/manifest.json"

if [[ ! -f "$manifest" ]]; then
  echo "Error: no existe manifest: $manifest" >&2
  exit 1
fi

mapfile -t client_paths < <(php -r '
$manifest = json_decode(file_get_contents($argv[1]), true);
if (!is_array($manifest) || !isset($manifest["clients"]) || !is_array($manifest["clients"])) {
    exit(1);
}
foreach ($manifest["clients"] as $client) {
    if (!is_array($client) || empty($client["enabled"]) || empty($client["path"])) {
        continue;
    }
    echo rtrim((string) $client["path"], "/") . PHP_EOL;
}
' "$manifest")

if [[ "${#client_paths[@]}" -eq 0 ]]; then
  echo "No hay clientes enabled=true en $manifest"
  exit 0
fi

for client_path in "${client_paths[@]}"; do
  echo "==> $client_path"
  "$script_dir/deploy-web-health.sh" "$client_path"
done

echo "Predeploy Salud Web terminado para ${#client_paths[@]} cliente(s)."
