---
- name: Expand /boot partition on target host
  hosts: all
  become: true
  gather_facts: true

  tasks:
    - name: Expand boot partition
      block:
        - name: Execute Bigboot role to resize /boot
          ansible.builtin.import_role:
            name: infra.lvm_snapshots.bigboot

      rescue:
        - name: Get the target device information and calculate padding
          ansible.builtin.set_fact:
            bigboot_shrink_target_info: "{{ ansible_facts.mounts \
              | selectattr('device', 'equalto', bigboot_shrink_target) | first }}"
            bigboot_size_padded: (bigboot_size | human_to_bytes * bigboot_shrink_padding) | int

        - name: Calculate the new logical volume size
          ansible.builtin.set_fact:
            shrink_lv_volume_size: "{{ (bigboot_shrink_target_info.size_total - bigboot_size_padded | int) \
              | ansible.builtin.human_readable | ansible.builtin.regex_replace(' ', '') }}"

        - name: Show resize information
          ansible.builtin.debug:
            msg: "Shrinking {{ bigboot_shrink_target }} from \
              {{ bigboot_shrink_target_info.size_total | ansible.builtin.human_readable }} to \
              {{ shrink_lv_volume_size[:-1] | ansible.builtin.regex_replace('^(\\d+)\\.\\d+(\\w).*', '\\1\\2') }} \
              to expand /boot partition by {{ bigboot_size }}."

        - name: Execute Shrink_LV role to resize target logical volume
          ansible.builtin.import_role:
            name: infra.lvm_snapshots.shrink_lv
          vars:
            shrink_lv_devices:
              - device: "{{ bigboot_shrink_target }}"
                size: "{{ shrink_lv_volume_size[:-1] \
                  | ansible.builtin.regex_replace('^(\\d+)\\.\\d+(\\w).*', '\\1\\2') }}"

        - name: Execute Bigboot role to resize /boot
          ansible.builtin.import_role:
            name: infra.lvm_snapshots.bigboot
