#!/usr/bin/env bash
# Behavior regression for phase-00-maas-recidr.sh (D-052/053 -> D-058). Fake maas + real jq.
set -uo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SCRIPT="$(cd "$HERE/../../scripts" && pwd)/phase-00-maas-recidr.sh"
BIN="$HERE/fakebin"; FIX="$HERE/fix"
chmod +x "$BIN"/* 2>/dev/null || true
command -v jq >/dev/null || { echo "FAIL: jq required"; exit 1; }
python3 "$HERE/make_fixtures.py" >/dev/null
rc_all=0; OUT="$(mktemp)"
run() { # want label scenario [--apply]
local want="$1" label="$2" s="$3"; shift 3
PATH="$BIN:$PATH" FIX_SUBNETS="$FIX/${s}_subnets.json" FIX_VLANS="$FIX/${s}_vlans.json" \
FIX_IPRANGES="$FIX/${s}_ipranges.json" FIX_IPADDRS="$FIX/${s}_ipaddrs.json" \
bash "$SCRIPT" "$@" >"$OUT" 2>&1
local rc=$?
if [ "$rc" -ne "$want" ]; then printf ' [XX] %-44s exit %s (want %s)\n' "$label" "$rc" "$want"; sed 's/^/ /' "$OUT"; rc_all=1; return 1; fi
printf ' [ok] %-44s exit %s\n' "$label" "$rc"; return 0
}
has() { grep -qE "$1" "$OUT" || { printf ' MISS /%s/\n' "$1"; rc_all=1; }; }
absent(){ grep -qE "$1" "$OUT" && { printf ' LEAK /%s/\n' "$1"; rc_all=1; } || true; }
before(){ local x y; x=$(grep -nE "$1" "$OUT"|head -1|cut -d: -f1); y=$(grep -nE "$2" "$OUT"|head -1|cut -d: -f1); { [ -n "$x" ] && [ -n "$y" ] && [ "$x" -lt "$y" ]; } || { printf ' ORDER /%s/ not before /%s/\n' "$1" "$2"; rc_all=1; }; }
echo "=== phase-00-maas-recidr.sh -- D-052/053 -> D-058 (fake maas + real jq) ==="
run 0 "pre-migration (d052): dry-run plan" d052
has 'metal-admin: 10\.12\.8\.0/22 .*fabric 2, vid 0. -> 10\.12\.12\.0/22'
has 'metal-internal: 10\.12\.12\.0/22 .*vid 103. -> 10\.12\.16\.0/22'
has 'data-tenant: 10\.12\.16\.0/22 .*fabric 3.*-> 10\.12\.20\.0/22'
has 'metal fabric .* = 2'
has 'data fabric .* = 3'
has 'reserved range ids to delete first: 100'
has 're-run with --apply'
absent 'DO:'
run 0 "pre-migration (d052): --apply, deletes BEFORE creates" d052 --apply
has 'DO: delete iprange 100'
has 'DO: delete subnet id=2'
has 'DO: create subnet 10\.12\.12\.0/22 on fabric 2 vid 0'
has 'DO: create subnet 10\.12\.16\.0/22 on fabric 2 vid 103'
has 'DO: create subnet 10\.12\.20\.0/22 on fabric 3 vid 0'
before 'MUTATE 1/2' 'MUTATE 2/2'
before 'DO: delete subnet id=4' 'DO: create subnet 10\.12\.12'
run 0 "migrated (done): nothing to migrate" done
has 'already migrated or not this plane; SKIP'
has 'nothing to migrate'
absent 'DO:'
absent 'WOULD:'
run 1 "wrong VID at old .12 -> refuse" wrongvid
has "subnet 10\.12\.12\.0/22 on VID '99', expected 103 -- refusing"
echo
[ "$rc_all" -eq 0 ] && echo "ALL PASS" || echo "SOME FAILED"
rm -f "$OUT"; exit "$rc_all"