- name: Update lvm configuration
  block:
  - name: Stringify snapshot_autoextend_percent setting
    ansible.builtin.set_fact:
      snapshot_create_snapshot_autoextend_percent_config: "activation/snapshot_autoextend_percent={{ snapshot_create_snapshot_autoextend_percent }}"
    when: snapshot_create_snapshot_autoextend_percent is defined
  - name: Stringify snapshot_autoextend_threshold setting
    ansible.builtin.set_fact:
      snapshot_create_snapshot_autoextend_threshold_config: "activation/snapshot_autoextend_threshold={{ snapshot_create_snapshot_autoextend_threshold }}"
    when: snapshot_create_snapshot_autoextend_threshold is defined
  - name: Stringify the new config
    ansible.builtin.set_fact:
      snapshot_create_new_lvm_config: >
        {{ snapshot_create_snapshot_autoextend_percent_config | default('') }}
         {{ snapshot_create_snapshot_autoextend_threshold_config | default('') }}
  - name: Set LVM configuration
    ansible.builtin.command: 'lvmconfig --mergedconfig --config "{{ snapshot_create_new_lvm_config }}" --file /etc/lvm/lvm.conf'
    changed_when: true
    when: ((snapshot_create_new_lvm_config | trim) | length) > 0

- name: Check for grubenv saved_entry
  ansible.builtin.lineinfile:
    name: /boot/grub2/grubenv
    regexp: ^saved_entry=
    state: absent
  check_mode: true
  changed_when: false
  failed_when: false
  register: snapshot_create_grubenv

- name: Add grubenv saved_entry
  ansible.builtin.shell: 'grubby --set-default-index=$(grubby --default-index)'
  changed_when: true
  when: snapshot_create_grubenv.found is defined and snapshot_create_grubenv.found == 0

- name: Create snapshots
  community.general.lvol:
    vg: "{{ item.vg }}"
    lv: "{{ item.lv }}"
    snapshot: "{{ item.lv }}_{{ snapshot_create_set_name }}"
    size: "{{ item.size | default(omit) }}"
  loop: "{{ snapshot_create_volumes }}"

- name: Required packages are present
  ansible.builtin.package:
    name:
    - gzip
    - tar
    state: present

- name: Create boot backup
  community.general.archive:
    format: gz
    mode: '0644'
    dest: "/root/boot-backup-{{ snapshot_create_set_name }}.tgz"
    path:
    - "/boot/initramfs-{{ ansible_kernel }}.img"
    - "/boot/vmlinuz-{{ ansible_kernel }}"
    - "/boot/System.map-{{ ansible_kernel }}"
    - "/boot/symvers-{{ ansible_kernel }}.gz"
    - "/boot/config-{{ ansible_kernel }}"
    - "/boot/.vmlinuz-{{ ansible_kernel }}.hmac"
    - /boot/grub/grub.conf
    - /boot/grub2/grub.cfg
    - /boot/grub2/grubenv
    - /boot/loader/entries
    - /boot/efi/EFI/redhat/grub.cfg
  when: snapshot_create_boot_backup
