#!/bin/bash

set -ex

# cleanup
(
    nmcli -f name connection | grep "^br\|^ovs\|^patch" | xargs nmcli connection delete
) &> /dev/null || :


cat<<EOF > /tmp/test.yaml
---
interfaces:
  - name: br-ex
    type: ovs-bridge
    state: up
    bridge:
      options:
        stp:
          enabled: true
      port:
        - name: patch-ex-to-phy
        - name: br-ex
  - name: br-phy
    type: ovs-bridge
    state: up
    bridge:
      options:
        stp:
          enabled: true
      port:
        - name: ovs-bond0
          link-aggregation:
            mode: balance-slb
            port:
              - name: enp7s0
              - name: enp11s0
        - name: patch-phy-to-ex
  - name: patch-phy-to-ex
    type: ovs-interface
    state: up
    patch:
      peer: patch-ex-to-phy
  - name: patch-ex-to-phy
    type: ovs-interface
    state: up
    patch:
      peer: patch-phy-to-ex 
  - name: br-ex
    type: ovs-interface
    state: up
    ipv4:
      enabled: true
      address:
        - ip: 192.0.2.1
          prefix-length: 24
EOF

i=0
while true; do
    i=$(( i + 1 ))

    nmstatectl apply /tmp/test.yaml

    j=0 
    while true; do
        j=$(( j + 1 ))
        printf "\n############### iteration $i.$j\n\n"
        systemctl restart NetworkManager
        sleep 2
        connected=0
        for t in $(seq 1 20); do
            sleep .5
            if ! ip addr show br-ex 2>/dev/null | grep "192.0.2.1" >/dev/null; then
                continue
            fi

            if [ "$(nmcli -g GENERAL.STATE connection show patch-ex-to-phy-if)" != activated ]; then
                continue
            fi

            connected=1
            break
        done
        if [ "$connected" = 0 ]; then
            nmcli device
            printf "\n\n\n *** ERROR: not connected at iteration $i.$j\n\n"
            exit 1
        fi
        [ "$j" = 10 ] && { sleep 5; break; }
    done
done

exit 0
