#!/bin/bash
set -euo pipefail

network_file="/etc/ngcp-config/network.yml"
echo "ngcp-upgrade: Checking network.yml for duplicate api_int types..."

errors=0

for host in $(yq -r '.hosts | keys[]' "$network_file"); do
  seen=()
  for iface in $(yq -r ".hosts.$host.interfaces[]" "$network_file"); do
    types=$(yq -r ".hosts.$host.$iface.type[]" "$network_file" 2>/dev/null || true)
    if [[ $types == *"api_int"* ]]; then
      seen+=("$host/$iface")
    fi
  done

  if [[ ${#seen[@]} -gt 1 ]]; then
    echo "Duplicate interface type $host/api_int (${seen[*]})" >&2
    errors=1
  fi
done

if [[ $errors == 1 ]]; then
  echo "ngcp-upgrade: Please fix these errors before proceeding." >&2
  exit 1
fi

echo "ngcp-upgrade: No duplicate api_int types found, proceeding."
