---

- name: get the datacenter name (<2.9)
  ovirt_datacenter_facts:
    auth: "{{ ovirt_auth }}"
    pattern: "Clusters.name = {{ providers.ovirt.cluster }}"

- name: get storage information (<2.9)
  ovirt_storage_domain_facts:
    auth: "{{ ovirt_auth }}"
    pattern: "datacenter={{ ovirt_datacenters[0].name }}"
  when:
    - template_disk_storage is undefined

- name: get data domain (<2.9)
  set_fact:
    disk_storage_domain: "{{ ovirt_storage_domains|json_query(the_query)|list|first }}"
  when:
    - template_disk_storage is undefined
  vars:
    the_query: "[?type=='data']"

- name: get iso domain (deprecated as of oVirt/RHV 4.3) (<2.9)
  set_fact:
    iso_domain: "{{ ovirt_storage_domains|json_query(the_query)|list|first }}"
  vars:
    the_query: "[?type=='iso']"

- name: check if template already exists (<2.9)
  ovirt_template_facts:
    auth: "{{ ovirt_auth }}"
    pattern: "name={{ template.name }} and datacenter={{ ovirt_datacenters[0].name }}"

- block:
    - name: set template_found to yes
      set_fact:
        template_found: yes

    - name: fail with message
      fail:
        msg: "Existing template found on ovirt/rhv: {{ template.name }}"
      when: not template_force|bool
  when:
    - ovirt_templates is defined
    - ovirt_templates | length > 0

- name: check iso file on data domain
  ovirt_disk_facts:
    auth: "{{ ovirt_auth }}"
    pattern: "name={{ iso_file_name }}"
  when: iso_file_name is defined

- debug:
    msg: "{{ ovirt_disks }}"

- name: set file id of the iso file
  set_fact:
    iso_file_id: "{{ ovirt_disks[0].id }}"
  when:
    - ovirt_disks | length > 0
    - ovirt_disks[0].id is defined
    - ovirt_disks[0].content_type == 'iso'

- name: fail with message
  fail:
    msg: "iso file ({{ iso_file_name }}) could not be found on the data domain and iso domain does not exists"
  when:
    - iso_file_id is undefined
    - iso_domain is undefined or iso_domain|length == 0