#!/usr/bin/env bash
# scripts/osd-blank-check.sh
#
# Read-only OSD secondary-disk blank check on the libvirt host (needs sudo for qemu-img).
# Confirms each host VM's OSD disk is wiped blank before redeploy so Ceph re-bootstraps clean.
# Override the image dir with IMGDIR=... if needed.
#
# Pinned host list comes from scripts/lib-hosts.sh (hostname-keyed).
# Exit codes: 0 all blank | 1 a disk looks non-blank | 2 a disk image missing

set -euo pipefail
shopt -s inherit_errexit 2>/dev/null || true
IFS=$'\n\t'

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=scripts/lib-net.sh
. "$SCRIPT_DIR/lib-net.sh"
# shellcheck source=scripts/lib-hosts.sh
. "$SCRIPT_DIR/lib-hosts.sh"

IMGDIR="${IMGDIR:-/var/lib/libvirt/images}"
RC=0
for h in "${HOSTS[@]}"; do
  img="$IMGDIR/${h}-1.qcow2"
  echo "== $h ($img) =="
  if [ ! -f "$img" ]; then echo "  FAIL: image not found"; RC=2; continue; fi
  info="$(sudo qemu-img info "$img")"
  # FIXED 2026-07-10 (full-project sweep): appended `|| true`. This file runs
  # under `set -euo pipefail` (line 11) -- if a real `qemu-img info` output
  # ever lacked both matched strings, grep would exit non-zero, pipefail
  # would propagate it, and this bare pipeline (inside the per-host loop)
  # would kill the WHOLE SCRIPT mid-loop rather than reaching the correctly
  # guarded gate logic below (lines 29-33, which do their own independent
  # awk extraction and don't depend on this line's exit status). Low
  # likelihood in practice (qemu-img's standard fields make this unlikely
  # to fire) but the same unguarded-pipe class as two other confirmed bugs
  # found in this same sweep -- fixed for consistency and defense in depth.
  echo "$info" | grep -E 'virtual size|disk size' | sed 's/^/  /' || true
  dsize="$(echo "$info" | awk -F': ' '/disk size/{print $2; exit}')"
  case "$dsize" in
    *KiB*|*bytes*) : ;;
    *) echo "  WARN: disk size '$dsize' looks non-blank (expected KiB)"; if [ "$RC" -eq 0 ]; then RC=1; fi ;;
  esac
done
echo
echo "expect: virtual 512 GiB, disk ~200 KiB (blank). RC=$RC"
exit "$RC"
