---
- name: SDN setup | Check if the HNS network exists
  register: hns_net_exists_out
  win_shell: >
    (Get-HNSNetwork | Where-Object { $_.Type -eq "Transparent" -and $_.Name -eq "{{ sdn_info.sdn_network_name }}" }) -ne $null

- name: SDN setup | Create HNS network if it doesn't exist
  block:
    - name: SDN setup | Create HNS network
      win_shell: >
        New-HnsNetwork -Name {{ sdn_info.sdn_network_name }} `
                       -AddressPrefix {{ ovn_subnet }} `
                       -Gateway {{ ovn_gateway_ip }} `
                       -Type Transparent `
                       -AdapterName "{{ interface_name }}"
      async: 10
      poll: 0

    # Wait for the HNS network creation. Connection will drop shortly when doing
    # this, wait for the connection to come back.
    - name: SDN setup | Wait for system to become reachable over WinRM (if network was created)
      wait_for_connection:
        # The connection should come back usually after a few seconds
        delay: 5
        timeout: 60
  when: (hns_net_exists_out.stdout | trim) == "False"

- name: SDN setup | Get the HNS network ID
  register: hns_net_id_out
  win_shell: |
    $ErrorActionPreference = "Stop"
    $net = Get-HNSNetwork | Where-Object { $_.Type -eq "Transparent" -and $_.Name -eq "{{ sdn_info.sdn_network_name }}" }
    if(!$net) {
        Throw "HNS network was not found"
    }
    if($net.Count -gt 1) {
        Throw "Multiple HNS networks were found"
    }
    $net.ID

- name: SDN setup | Set the HNS network ID fact
  set_fact:
    hns_net_id: "{{ hns_net_id_out.stdout | trim }}"

- name: SDN setup | Restart Docker to get the latest HNS networks
  win_service:
    name: Docker
    state: restarted
