- name: Teardown Windows code coverage configuration
  hosts: all
  gather_facts: no
  tasks:
  - name: Zip up all coverage files
    ansible.windows.win_shell: |
      $coverage_dir = '{{ remote_temp_path }}'
      $zip_file = Join-Path -Path $coverage_dir -ChildPath 'coverage.zip'
      if (Test-Path -LiteralPath $zip_file) {
          Remove-Item -LiteralPath $zip_file -Force
      }

      $coverage_files = Get-ChildItem -LiteralPath $coverage_dir -Include '*=coverage*' -File

      $legacy = $false
      try {
          # Requires .NET 4.5+ which isn't present on older WIndows versions. Remove once 2008/R2 is EOL.
          # We also can't use the Shell.Application as it will fail on GUI-less servers (Server Core).
          Add-Type -AssemblyName System.IO.Compression -ErrorAction Stop > $null
      } catch {
          $legacy = $true
      }

      if ($legacy) {
          New-Item -Path $zip_file -ItemType File > $null
          $shell = New-Object -ComObject Shell.Application
          $zip = $shell.Namespace($zip_file)
          foreach ($file in $coverage_files) {
              $zip.CopyHere($file.FullName)
          }
      } else {
          $fs = New-Object -TypeName System.IO.FileStream -ArgumentList $zip_file, 'CreateNew'
          try {
              $archive = New-Object -TypeName System.IO.Compression.ZipArchive -ArgumentList @(
                  $fs,
                  [System.IO.Compression.ZipArchiveMode]::Create
              )
              try  {
                  foreach ($file in $coverage_files) {
                      $archive_entry = $archive.CreateEntry($file.Name, 'Optimal')
                      $entry_fs = $archive_entry.Open()
                      try {
                          $file_fs = [System.IO.File]::OpenRead($file.FullName)
                          try {
                              $file_fs.CopyTo($entry_fs)
                          } finally {
                              $file_fs.Dispose()
                          }
                      } finally {
                          $entry_fs.Dispose()
                      }
                  }
              } finally {
                  $archive.Dispose()
              }
          } finally {
              $fs.Dispose()
          }
      }

  - name: Fetch coverage zip
    fetch:
      src: '{{ remote_temp_path }}\coverage.zip'
      dest: '{{ local_temp_path }}/{{ inventory_hostname }}.zip'
      flat: yes

  - name: Remove temporary coverage directory
    ansible.windows.win_file:
      path: '{{ remote_temp_path }}'
      state: absent
