---
- name: Install tpm2-tools and dracut
  ansible.builtin.apt:
    name:
      - tpm2-tools
      - dracut

- name: Enable tpm2-tss crypt module on dracut
  ansible.builtin.copy:
    dest: /etc/dracut.conf.d/crypt.conf
    content: add_dracutmodules+=" tpm2-tss crypt "
    mode: '0644'
  notify: Run update-dracut

- name: Comment out root device in crypttab
  ansible.builtin.lineinfile:
    dest: /etc/crypttab
    regexp: '^([^#].*)'
    line: '#\1'
    backrefs: true

- name: Insert luks support to GRUB_CMDLINE_LINUX
  ansible.builtin.lineinfile:
    dest: /etc/default/grub
    regexp: '^(GRUB_CMDLINE_LINUX=).*'
    line: '\1"rd.auto rd.luks=1"'
    backrefs: true
  notify: Run update-grub

- name: Insert TPM2 to Luks slot
  ansible.builtin.command:
    cmd: >
      systemd-run -P --wait
      -p SetCredential=cryptenroll.passphrase:{{ encrypt_passphrase | default(encrypt_passphrase_initial) }}
      systemd-cryptenroll --tpm2-device=auto --tpm2-pcrs="" {{ encrypt_device }} --wipe-slot=tpm2
  no_log: true
  when: "'tpm2' not in encrypt_slots_result.stdout"

# - name: Update TPM2 Luks slot
#   ansible.builtin.command:
#     cmd: systemd-cryptenroll --tpm2-device=auto --tpm2-pcrs=7+8 --unlock-tpm2-device=auto {{ encrypt_device }} --wipe-slot=tpm2
#   when: not grub_config.changed
