---
- name: Find device with LUKS holder
  vars:
    partitions: "{{ item.value.partitions | dict2items | selectattr('value.holders', 'search', 'luks|crypt') }}"
  ansible.builtin.set_fact:
    encrypt_device: "/dev/disk/by-id/{{ partitions[0].value.links.ids[0] }}"
  when:
    - item.value.partitions is defined
    - item.value.partitions | dict2items | length > 0
    - item.value.partitions | dict2items | selectattr('value.holders', 'search', 'luks|crypt') | length > 0
  loop: "{{ ansible_devices | dict2items }}"

- name: Get luks slots
  ansible.builtin.command:
    cmd: "systemd-cryptenroll {{ encrypt_device }}"
  register: encrypt_slots_result
  changed_when: false
  when: encrypt_device is defined

- name: Change Password of Luks password slot
  ansible.builtin.command:
    cmd: >
      systemd-run -P --wait
      -p SetCredential=cryptenroll.passphrase:{{ encrypt_passphrase_initial }}
      -p SetCredential=cryptenroll.new-passphrase:{{ encrypt_passphrase }}
      systemd-cryptenroll --password {{ encrypt_device }} --wipe-slot=password
  no_log: true
  when:
    - encrypt_device is defined
    - encrypt_passphrase is defined
    - encrypt_slots_result.stdout_lines | length == 2
    - encrypt_slots_result.stdout_lines[1].startswith('   0')

- name: TPM Device Check
  ansible.builtin.stat:
    path: /dev/tpm0
  register: tpm_device
  when: encrypt_device is defined

- name: Include TPM2 role
  ansible.builtin.include_tasks:
    file: tpm2.yml
  when:
    - encrypt_device is defined
    - encrypt_tpm2
    - tpm_device.stat.exists
