---
- name: Cleanup neutron router and dhcp interfaces
  shell: |
    ovs-vsctl list interface | awk '/name[ ]*: qr-|ha-|qg-|rfp-|sg-|fg-/ { print $3 }' | xargs -n1 ovs-vsctl del-port

    # dhcp tap ports cannot be easily distinguished from ovsfw ports, so we
    # list them from within the qdhcp namespaces
    for netns in `ip netns  | awk '{ print $1 }' | grep qdhcp-`; do
      for dhcp_port in `ip netns exec $netns ip -o link show | awk -F': ' '{print $2}' | grep tap`; do
        ovs-vsctl del-port $dhcp_port
      done
    done
  register: router_dhcp_error
  ignore_errors: True

- name: Cleanup neutron router and dhcp interfaces finished
  debug:
    msg: WARNING error while cleaning ovs interface with msg {{ router_dhcp_error.msg }}
  when:
    - router_dhcp_error.changed
    - router_dhcp_error.rc != 0

- name: Check if neutron trunk subports need cleanup
  shell: |
    ovs-vsctl list interface | awk '/name[ ]*: sp[it]-/ { print $3 }' | grep 'spi-\|spt-'
  register: do_cleanup
  ignore_errors: True

- name: Cleanup neutron trunk subports
  when: do_cleanup.rc == 0
  shell: |
    ovs-vsctl list interface | awk '/name[ ]*: sp[it]-/ { print $3 }' | xargs -n1 ovs-vsctl del-port
  register: trunk_error
  ignore_errors: True

- name: Cleanup trunk ports finished
  debug:
    msg: WARNING error while cleaning ovs interface with msg {{ trunk_error.msg }}
  when:
    - trunk_error.changed
    - trunk_error.rc != 0

- name: Clean neutron datapath security groups from iptables
  shell: |
    {{ iptables_exec }}-save > /tmp/iptables-before-cleanup
    cat /tmp/iptables-before-cleanup | grep -v neutron-openvswi | \
        grep -v neutron-filter > /tmp/iptables-after-cleanup

    if ! cmp /tmp/iptables-before-cleanup /tmp/iptables-after-cleanup
    then
      cat /tmp/iptables-after-cleanup | {{ iptables_exec }}-restore
      echo "Security groups cleaned"
    fi
  register: out
  with_items:
    - iptables
    - ip6tables
  loop_control:
    loop_var: iptables_exec
  changed_when: "'Security groups cleaned' in out.stdout"

- name: Cleanup neutron datapath resources
  become: yes
  shell: |
    for container in $(podman ps -a --format {% raw %}"{{.ID}}"{% endraw %} --filter "name=(neutron-(dibbler|dnsmasq|haproxy|keepalived)-.*|dhcp_dnsmasq|dhcp_haproxy|l3_keepalived|l3_haproxy|l3_dibbler|l3_radvd)"); do
        echo "Cleaning up side-car container $container"
        podman stop $container
        podman rm -f $container
    done

    # cleanup Neutron ml2/ovs namespaces
    for netns in $(ip netns | awk '/^(snat|fip|qdhcp|qrouter)-/{ print $1 }'); do
        echo "Cleaning up namespace $netns"
        ip netns delete $netns
    done
