---
- name: Get the backing device path
  command: >-
    realpath /dev/disk/by-uuid/{{ _storage_test_pool_member_path |
      regex_replace('^.*/luks-', '') }}
  register: _storage_test_member_backing_dev
  changed_when: false
  when:
    - storage_test_pool.encryption
    - storage_test_pool.state =='present'

- name: Ensure cryptsetup is present
  package:
    name: cryptsetup
    state: present
    use: "{{ (__storage_is_ostree | d(false)) | ternary('ansible.posix.rhel_rpm_ostree', omit) }}"

- name: Collect LUKS info for this member
  command: cryptsetup luksDump {{ _storage_test_member_backing_dev.stdout }}
  register: _storage_test_luks_dump
  when:
    - storage_test_pool.encryption
    - storage_test_pool.state == 'present'
  changed_when: false

- name: Check LUKS version
  assert:
    that: _storage_test_luks_dump.stdout is search(__pattern, multiline=True)
    msg: Wrong LUKS version for pool {{ storage_test_pool.name }}
  vars:
    __ver: "{{ storage_test_pool.encryption_luks_version | replace('luks', '') }}"
    __pattern: "^Version:\\s+{{ __ver }}$"
  when:
    - storage_test_pool.state == 'present'
    - storage_test_pool.encryption
    - not storage_test_pool.encryption_luks_version is none
    - storage_test_pool.encryption_luks_version | length > 0

- name: Check LUKS key size
  assert:
    that: _storage_test_luks_dump.stdout is search(__pattern, multiline=True)
    msg: Wrong key size for pool {{ storage_test_pool.name }}
  vars:
    __key_size: "{{ storage_test_pool.encryption_key_size | string }}"
    __pattern: "{{ '^MK bits:\\s+' ~ __key_size ~ '$' if storage_test_pool.encryption_luks_version | d('luks1') == 'luks1' else '^\\s+Key:\\s+' ~ __key_size ~ ' bits$' }}"
  when:
    - storage_test_pool.state == 'present'
    - storage_test_pool.encryption
    - not storage_test_pool.encryption_key_size is none
    - storage_test_pool.encryption_key_size > 0

- name: Check LUKS cipher
  assert:
    that: _storage_test_luks_dump.stdout is search(__pattern, multiline=True)
    msg: Wrong cipher for pool {{ storage_test_pool.name }}
  vars:
    __cipher: "{{ storage_test_pool.encryption_cipher.split('-')[1:] | join('-') if storage_test_pool.encryption_luks_version | d('luks1') == 'luks1' else storage_test_pool.encryption_cipher }}"
    __pattern: "{{ '^Cipher mode:\\s+' ~ __cipher ~ '$' if storage_test_pool.encryption_luks_version | d('luks1') == 'luks1' else '^\\s+Cipher:\\s+' ~ __cipher ~ '$' }}"
  when:
    - storage_test_pool.state == 'present'
    - storage_test_pool.encryption
    - not storage_test_pool.encryption_cipher is none
    - storage_test_pool.encryption_cipher | length > 0
