---
- name: Ensure test packages
  package:
    name: "{{ test_packages }}"
    state: present
    use: "{{ (__storage_is_ostree | d(false)) |
             ternary('ansible.posix.rhel_rpm_ostree', omit) }}"
  vars:
    # util-linux needed for lsblk, findmnt, etc.
    test_packages: "{{ ['util-linux-core']
      if (ansible_facts['os_family'] == 'RedHat' and
          ansible_facts['distribution_major_version'] is version('8', '>'))
      else ['util-linux'] if ansible_facts['os_family'] == 'RedHat'
      else ['util-linux'] }}"

- name: Find unused disks in the system
  find_unused_disk:
    min_size: "{{ min_size | d(omit) }}"
    max_size: "{{ max_size | d(omit) }}"
    max_return: "{{ max_return | d(omit) }}"
    with_interface: "{{ storage_test_use_interface | d(omit) }}"
    match_sector_size: "{{ match_sector_size | d(omit) }}"
  register: unused_disks_return

- name: Debug why there are no unused disks
  shell: |
    set -x
    exec 1>&2
    lsblk -p --pairs --bytes -o NAME,TYPE,SIZE,FSTYPE,LOG-SEC
    journalctl -ex
  changed_when: false
  when: "'Unable to find unused disk' in unused_disks_return.disks"

- name: Set unused_disks if necessary
  set_fact:
    unused_disks: "{{ unused_disks_return.disks }}"
  when: "'Unable to find unused disk' not in unused_disks_return.disks"

- name: Exit playbook when there's not enough unused disks in the system
  fail:
    msg: "Unable to find enough unused disks. Exiting playbook."
  when: unused_disks | d([]) | length < disks_needed | d(1)

- name: Print unused disks
  debug:
    var: unused_disks
