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

SELF_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=/usr/local/libexec/brixcli/common.sh
source "${SELF_DIR}/common.sh"

job="${1:?usage: broadcast-run <job-name>}"
load_config
ensure_runtime_dirs
validate_job_name "${job}"

command_file="${BROADCAST_DIR}/${job}.command"
[[ -f "${command_file}" ]] || die "missing broadcast command file: ${command_file}"

command_string="$(<"${command_file}")"
[[ -n "${command_string}" ]] || die "broadcast command file is empty: ${command_file}"

declare -a pids=()
declare -a agents=()
failed=0

while IFS=: read -r agent port created_at; do
  [[ -n "${agent:-}" ]] || continue

  (
    printf '[broadcast:%s][%s] START %s\n' "${job}" "${agent}" "$(date -Iseconds)"
    if runuser -u "${agent}" -- bash -lc "${command_string}"; then
      rc=0
    else
      rc=$?
    fi
    printf '[broadcast:%s][%s] END rc=%s %s\n' "${job}" "${agent}" "${rc}" "$(date -Iseconds)"
    exit "${rc}"
  ) &
  pids+=("$!")
  agents+=("${agent}")
done <"${AGENTS_DB}"

for idx in "${!pids[@]}"; do
  if ! wait "${pids[$idx]}"; then
    printf '[broadcast:%s][%s] FAILED\n' "${job}" "${agents[$idx]}" >&2
    failed=1
  fi
done

exit "${failed}"
