#!/usr/bin/env bash
# Ordered host-seat spill primitive. The callback must pin its dispatch to the
# supplied host and return a retryable status only when that seat did not run work.

fleet_seat_retryable() {
  local status="$1" retryable=",${2},"
  [[ "$retryable" == *",${status},"* ]]
}

fleet_seat_run() {
  local hosts_csv="$1" retryable="$2" callback="$3"
  local host status last_status=97
  local -a hosts=()

  IFS=',' read -r -a hosts <<<"$hosts_csv"
  [[ ${#hosts[@]} -gt 0 ]] || return 97

  for host in "${hosts[@]}"; do
    [[ -n "$host" ]] || continue
    if "$callback" "$host"; then
      return 0
    else
      status=$?
    fi
    last_status="$status"
    if ! fleet_seat_retryable "$status" "$retryable"; then
      return "$status"
    fi
    printf 'fleet-seat: %s unavailable (exit %s); spilling to next host\n' "$host" "$status" >&2
  done

  return "$last_status"
}
