#!/bin/bash
# pg_preflight_batch.sh — 接 N 個 target args，並行 ssh preflight check
#
# 用法：
#   pg_preflight_batch.sh TARGET1 TARGET2 ...
#
# 每個 target 跑 pg_preflight_check.sh，並行執行（最多 10 個），輸出每行 1 個 JSON

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PREFLIGHT_SCRIPT="${SCRIPT_DIR}/pg_preflight_check.sh"

[[ ! -x "$PREFLIGHT_SCRIPT" ]] && { echo "{\"error\":\"pg_preflight_check.sh not executable\"}"; exit 1; }
[[ $# -eq 0 ]] && { echo "{\"error\":\"no targets\"}"; exit 1; }

# 並行：用 wait 控制最多 10 同時
MAX_CONCURRENT=10
running=0
for target in "$@"; do
    "$PREFLIGHT_SCRIPT" "$target" &
    running=$((running + 1))
    if (( running >= MAX_CONCURRENT )); then
        wait -n 2>/dev/null || wait  # 等任一個完成（或舊版 bash 全等）
        running=$((running - 1))
    fi
done
wait
