---
- name: Make sure the required related facts are available
  ansible.builtin.setup:
    gather_subset:
    - "!all"
    - "!min"
    - kernel

- name: Get kernel version
  ansible.builtin.set_fact:
    initramfs_kernel_version: "{{ ansible_facts.kernel }}"

- name: Create a backup of the current initramfs
  ansible.builtin.copy:
    remote_src: true
    src: /boot/initramfs-{{ initramfs_kernel_version }}.img
    dest: /boot/initramfs-{{ initramfs_kernel_version }}.img.{{ initramfs_backup_extension }}
    mode: "0600"

- name: Create a new initramfs with the optional additional modules
   # yamllint disable-line rule:line-length
  ansible.builtin.command: '/usr/bin/dracut {{ ((initramfs_add_modules | length) > 0) | ternary("-a", "") }} "{{ initramfs_add_modules }}" --kver {{ initramfs_kernel_version }} --force'
  changed_when: true

- name: Reboot the server
  ansible.builtin.reboot:
    post_reboot_delay: "{{ initramfs_post_reboot_delay }}"
    reboot_timeout: "{{ initramfs_reboot_timeout }}"

- name: Restore previous initramfs
  ansible.builtin.copy:
    remote_src: true
    src: /boot/initramfs-{{ initramfs_kernel_version }}.img.{{ initramfs_backup_extension }}
    dest: /boot/initramfs-{{ initramfs_kernel_version }}.img
    mode: "0600"

- name: Remove initramfs backup file
  ansible.builtin.file:
    path: /boot/initramfs-{{ initramfs_kernel_version }}.img.{{ initramfs_backup_extension }}
    state: absent
