---
- name: OVS HNS network setup | Remove setup_ovs_hns script and its log if they exists
  win_file:
    path: "{{ item }}"
    state: absent
  with_items:
    - "{{ install_path }}/setup_ovs_hns.ps1"
    - "{{ install_path }}/setup_ovs_hns.log"

- name: OVS HNS network setup | Create setup_ovs_hns script
  win_lineinfile:
    path: "{{ install_path }}/setup_ovs_hns.ps1"
    create: yes
    line: |
      $ErrorActionPreference = "Stop"
      #
      # Enable OVS on HNS network
      #
      $net = Get-HnsNetwork | Where-Object { $_.ID -eq "{{ hns_net_id }}" }
      Set-Service "ovs-vswitchd" -StartupType Disabled
      Stop-Service "ovs-vswitchd" -Force
      Disable-OVSOnHNSNetwork $net.ID
      $bridgeName = "vEthernet ($($net.NetworkAdapterName))"
      ovs-vsctl.exe --no-wait --if-exists del-br "$bridgeName"
      if($LASTEXITCODE) {
          Throw "Failed to cleanup existing OVS bridge"
      }
      ovs-vsctl.exe --no-wait add-br "$bridgeName"
      if($LASTEXITCODE) {
          Throw "Failed to add the OVS bridge"
      }
      ovs-vsctl.exe --no-wait add-port "$bridgeName" "$($net.NetworkAdapterName)"
      if($LASTEXITCODE) {
          Throw "Failed to add the HNS interface to OVS bridge"
      }
      Enable-OVSOnHNSNetwork $net.ID
      Set-Service "ovs-vswitchd" -StartupType Automatic
      Start-Service "ovs-vswitchd"
      #
      # Set the OVS guid and the k8s-api-server
      #
      ovs-vsctl.exe get Open_vSwitch . external_ids:system-id
      if($LASTEXITCODE -ne 0) {
          # The system-id guid is not set is $LASTEXITCODE is different than zero
          ovs-vsctl.exe --timeout {{ ovs_cmd_timeout }} set Open_vSwitch . external_ids:system-id="$((New-Guid).Guid)"
          if($LASTEXITCODE) {
              Throw "Failed to set the OVS system-id guid"
          }
      }
      ovs-vsctl.exe --timeout {{ ovs_cmd_timeout }} set Open_vSwitch . external_ids:k8s-api-server="http://{{ kubernetes_info.MASTER_IP }}:8080"
      if($LASTEXITCODE) {
          Throw "Failed to set the k8s-api-server"
      }
      #
      # Create the OVS tunnel
      #
      ovs-vsctl.exe --timeout {{ ovs_cmd_timeout }} set Open_vSwitch . `
              external_ids:ovn-remote="tcp:{{ kubernetes_info.MASTER_IP }}:6642" `
              external_ids:ovn-nb="tcp:{{ kubernetes_info.MASTER_IP }}:6641" `
              external_ids:ovn-encap-ip={{ host_public_ip }} `
              external_ids:ovn-encap-type="geneve"
      if($LASTEXITCODE) {
          Throw "Failed to create the OVS tunnel"
      }
    newline: unix

- name: OVS HNS network setup | Run setup_ovs_hns script
  win_psexec:
    executable: "{{ install_path }}/PSTools/PsExec64.exe"
    command: cmd /c powershell.exe {{ install_path }}/setup_ovs_hns.ps1 2>&1 >> {{ install_path }}/setup_ovs_hns.log
    interactive: no
    system: yes
    wait: yes
    timeout: 120
