#!/usr/bin/env bash
# Fleet bootstrap of the `infra-ops` agent identity across PFI-OWNED boxes.
# Runs playbooks/bootstrap-infra-ops-user.yaml on each host via elway.
#
# RUN THIS YOURSELF (operator). Each host's first bootstrap needs YOUR sudo, so
# elway prompts for your sudo password once per host (lazy). After bootstrap the
# agent authenticates as `infra-ops` with its own key (NOPASSWD) and never needs
# your password again — re-runs are then promptless and idempotent.
#
# Usage:
#   scripts/bootstrap-infra-ops-fleet.sh                 # tiers 1+2 (default)
#   PFI_TIER=compute scripts/bootstrap-infra-ops-fleet.sh   # tier 1 only
#   PFI_TIER=all     scripts/bootstrap-infra-ops-fleet.sh   # + tier 3 sensitive infra
#   scripts/bootstrap-infra-ops-fleet.sh irv-ml1            # explicit host(s)
#
# SCOPE — PFI-owned Linux boxes ONLY. This list deliberately EXCLUDES:
#   SureFire sf-*/sfsrv-ana (tenant), corviduo-dev (partner app-layer),
#   esh-* (non-PFI home lab), nh3-nas (Synology DSM — no useradd/sudoers.d).
# Hosts must resolve as ssh aliases (or be reachable as your account).

set -uo pipefail
cd "$(dirname "$0")/.."

PLAYBOOK=playbooks/bootstrap-infra-ops-user.yaml

# Tier 1 — compute / docker hosts (where the agent recurs)
TIER1=(irv-ml1 ana-ml2 ana-docker nh3-docker nh3-dev)
# Tier 2 — PFI app VMs / LXCs
TIER2=(pfi-ana-webhost ana-filebot pfi-pteradactyl pfi-tacticalrmm ana-nas)
# Tier 3 — sensitive infra (DB, backup, network, hypervisors): opt-in via PFI_TIER=all
TIER3=(pfi-postgres pbs-ana pbs-nh3 ana-wg pfi-pve nh3-pve)

if [ "$#" -gt 0 ]; then
  HOSTS=("$@")
else
  case "${PFI_TIER:-default}" in
    compute) HOSTS=("${TIER1[@]}") ;;
    all)     HOSTS=("${TIER1[@]}" "${TIER2[@]}" "${TIER3[@]}") ;;
    *)       HOSTS=("${TIER1[@]}" "${TIER2[@]}") ;;
  esac
fi

echo "infra-ops fleet bootstrap → ${#HOSTS[@]} host(s):"
printf '  %s\n' "${HOSTS[@]}"
echo

declare -a OK=() FAIL=()
for h in "${HOSTS[@]}"; do
  echo "================ $h ================"
  if scripts/elway "$h" --playbook "$PLAYBOOK"; then
    OK+=("$h")
  else
    FAIL+=("$h")
    echo "!! bootstrap FAILED on $h (continuing)"
  fi
  echo
done

echo "================ summary ================"
echo "ok   (${#OK[@]}): ${OK[*]:-none}"
echo "fail (${#FAIL[@]}): ${FAIL[*]:-none}"
[ "${#FAIL[@]}" -eq 0 ]
