#!/usr/bin/env bash
# Read-only ONTAP CLI collector. Requires SSH public-key access and a CSV inventory.
set -uo pipefail
inventory="${1:-inventory.csv}"
report_dir="${2:-reports}"
ssh_user="${ONTAP_SSH_USER:-}"
if [[ -z "$ssh_user" || ! -r "$inventory" ]]; then
  printf 'Usage: ONTAP_SSH_USER=monitor %s inventory.csv reports/\n' "$0" >&2
  exit 2
fi
mkdir -p -- "$report_dir" || exit 2
status=0
while IFS=, read -r cluster address extra || [[ -n "$cluster" ]]; do
  cluster="${cluster%$'\r'}"; address="${address%$'\r'}"
  [[ "$cluster" == Cluster && "$address" == Address ]] && continue
  [[ -z "$cluster" && -z "$address" ]] && continue
  if [[ -n "$extra" || ! "$cluster" =~ ^[a-zA-Z0-9_-]+$ || ! "$address" =~ ^[a-zA-Z0-9.:-]+$ ]]; then
    printf 'Invalid inventory row for %s\n' "$cluster" >&2
    status=1; continue
  fi
  target="$ssh_user@$address"
  stamp="$(date -u +%Y%m%dT%H%M%SZ)"
  output="$report_dir/${cluster}-${stamp}.txt"
  {
    printf 'Cluster: %s (%s)\nUTC: %s\n' "$cluster" "$address" "$stamp"
    for command in 'cluster show' 'storage failover show' 'system health alert show' 'storage aggregate show' 'volume show' 'snapmirror show'; do
      printf '\n### %s\n' "$command"
      # SSH verifies host keys by default. BatchMode requires a preinstalled key.
      if ! ssh -o BatchMode=yes -o ConnectTimeout=10 -- "$target" "$command"; then
        printf 'ERROR: SSH command failed: %s\n' "$command"
        status=1
      fi
    done
  } > "$output" 2>&1
  printf 'Wrote %s\n' "$output"
done < "$inventory"
printf 'Review alerts, HA readiness, free capacity and replication lag in each report.\n'
exit "$status"
