#!/usr/bin/env bash
# scripts/opentofu-validate.sh [tofu-dir]
#
# Thin syntax/schema gate for opentofu/ (VR1 IaC, D-103). Read-only: runs
# `tofu fmt -check` + `tofu init -backend=false` + `tofu validate` against the
# root module. Does NOT plan or apply -- no provider connection, no libvirt
# reach required. This is the harness opentofu/README.md tells you to run
# before trusting anything under opentofu/, since it was authored in a
# session with no tofu binary available to self-check.
#
# Exit: 0 clean | 1 fmt/init/validate failed | 2 tofu binary not found.
set -uo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TOFU_DIR="${1:-$HERE/../opentofu}"

if [ ! -d "$TOFU_DIR" ]; then
  echo "FAIL: no such directory: $TOFU_DIR"
  exit 1
fi

if ! command -v tofu >/dev/null 2>&1; then
  echo "FAIL: tofu binary not found on PATH -- install OpenTofu, then re-run this script"
  exit 2
fi

fail=0

echo "== tofu fmt -check -recursive =="
if ! tofu fmt -check -recursive -diff "$TOFU_DIR"; then
  echo "  [FAIL] formatting drift -- run: tofu fmt -recursive $TOFU_DIR"
  fail=1
fi

echo "== tofu init -backend=false (downloads providers; needs registry network access) =="
if ! ( cd "$TOFU_DIR" && tofu init -backend=false -input=false ); then
  echo "  [FAIL] init failed"
  exit 1
fi

echo "== tofu validate =="
if ! ( cd "$TOFU_DIR" && tofu validate ); then
  echo "  [FAIL] validate failed"
  fail=1
fi

if [ "$fail" -eq 0 ]; then
  echo "PASS: opentofu-validate ($TOFU_DIR)"
  exit 0
else
  echo "FAIL: opentofu-validate ($TOFU_DIR)"
  exit 1
fi
