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

red() { printf "\033[31m%s\033[0m\n" "$*"; }
grn() { printf "\033[32m%s\033[0m\n" "$*"; }
yel() { printf "\033[33m%s\033[0m\n" "$*"; }

ROOT_DIR=$(cd "$(dirname "$0")/../.." && pwd)
cd "$ROOT_DIR"

fail=0

# Validate YAML via docker stack config
while IFS= read -r -d '' file; do
  yel "Validating: $file"
  if docker stack config -c "$file" >/dev/null 2>&1; then
    grn "OK: $file"
  else
    red "ERROR: docker stack config failed for $file"
    fail=1
  fi

  # Check external networks referenced exist
  nets=$(awk '/networks:/,/^$/' "$file" | awk '/external: true/{print prev}{prev=$1}' | sed 's/://g' | sed 's/^[[:space:]]*//g' | sort -u || true)
  for n in $nets; do
    if docker network inspect "$n" >/dev/null 2>&1; then
      grn "  network OK: $n"
    else
      yel "  network MISSING: $n"
    fi
  done

  # Check external secrets referenced exist
  secs=$(awk '/secrets:/,/^$/' "$file" | awk '/external: true/{print prev}{prev=$1}' | sed 's/://g' | sed 's/^[[:space:]]*//g' | sort -u || true)
  for s in $secs; do
    if docker secret inspect "$s" >/dev/null 2>&1; then
      grn "  secret OK: $s"
    else
      yel "  secret MISSING: $s"
    fi
  done

done < <(find stacks -type f -name "*.yml" -print0 | sort -z)

# List NFS volumes for operator verification
yel "NFS volumes referenced (verify exports exist on omv800.local):"
grep -R "device: :/export/" -n stacks || true

exit $fail
