# scripts/lib-net.sh
#
# Single source of truth for v1 (VR0 / Baldurkeep) pinned network values.
# SOURCED by discovery / verify scripts -- not executed directly. ASCII + LF.
# Authoritative per D-052 / D-053 (matches bundle.yaml at committed HEAD).
# Contains constants + tiny read-only helpers ONLY. No mutations, no state changes.
#
# CIDR is the stable key throughout: MAAS subnet IDs drift across cutovers
# (the D-052 cutover moved metal-internal to id=10, not the old id=6), so every
# lookup resolves BY CIDR, never by a hardcoded subnet ID. (PATTERN-1.)

# shellcheck shell=bash
# shellcheck disable=SC2034  # constants consumed by sourcing scripts

# Guard: refuse to run directly (it is a library).
if [ "${BASH_SOURCE[0]:-}" = "${0}" ]; then
  echo "lib-net.sh is a sourced library; do not run it directly." >&2
  exit 2
fi

# --- The six MAAS spaces / planes (D-052 / D-053). ---
PLANE_CIDRS=( "10.12.4.0/22" "10.12.8.0/22" "10.12.12.0/22" "10.12.16.0/22" "10.12.32.0/22" "10.12.36.0/22" )
declare -A PLANE_NAME=(
  ["10.12.4.0/22"]="provider-public"
  ["10.12.8.0/22"]="metal-admin"
  ["10.12.12.0/22"]="metal-internal"
  ["10.12.16.0/22"]="data-tenant"
  ["10.12.32.0/22"]="storage"
  ["10.12.36.0/22"]="replication"
)
SPACES6=( provider-public metal-admin metal-internal data-tenant storage replication )

# Names that MUST be gone after the D-052 / D-053 cutover (deploy fails or mis-binds if any reappear).
STALE_SPACES=( provider metal data fabric-data lbaas )

# Gateways: only provider-public and metal-admin route; the other four are gw=none.
declare -A PLANE_GW=( ["10.12.4.0/22"]="10.12.4.1" ["10.12.8.0/22"]="10.12.8.1" )

# The four non-API, non-PXE planes whose host NICs MAAS must have provisioned.
DATA_PLANE_CIDRS=( "10.12.12.0/22" "10.12.16.0/22" "10.12.32.0/22" "10.12.36.0/22" )

# metal-internal is a TAGGED VLAN bridged on the metal fabric; host links land on br-internal.
METAL_INTERNAL_CIDR="10.12.12.0/22"
METAL_INTERNAL_VID="103"
METAL_INTERNAL_IFACE="br-internal"

# Host identity (hostnames, octets, boot MACs, system_id resolution) now lives in
# scripts/lib-hosts.sh, keyed by HOSTNAME -- system_ids are re-minted on every
# (re-)enrollment, so the old SYSID-keyed maps here were a landmine and were retired
# (DOCFIX-040). Source lib-hosts.sh for HOSTS / HOST_OCTET / host_sysid().

# Triple HA VIPs (D-020 + D-052): each API charm carries provider/admin/internal columns,
# matching last octet, in the .50-.60 band. 11 clustered API charms.
VIP_PREFIX_PROVIDER="10.12.4"
VIP_PREFIX_ADMIN="10.12.8"
VIP_PREFIX_INTERNAL="10.12.12"
VIP_OCTET_MIN=50
VIP_OCTET_MAX=60
VIP_COUNT_EXPECT=11

# --- tiny read-only helpers ---

# need_jq: jq is required (present on the jumphost). Returns non-zero if absent.
need_jq() {
  command -v jq >/dev/null 2>&1 || { echo "FAIL: jq not found on PATH (jumphost should have it)" >&2; return 1; }
}

# fourth_octet <ip>: echo the last dotted octet of an IPv4 address.
fourth_octet() { local ip="$1"; echo "${ip##*.}"; }
