---
- name: Get /boot mount information
  ansible.builtin.set_fact:
    bigboot_boot_mount: "{{ ansible_facts.mounts \
      | selectattr('mount', 'equalto', '/boot') | first }}"

- name: Capture device for /boot
  ansible.builtin.set_fact:
    bigboot_boot_device: "{{ bigboot_boot_mount.device | regex_replace('^.*/(\\w+$)', '\\1') }}"

- name: Capture partition size for /boot parition
  ansible.builtin.set_fact:
    bigboot_boot_partsize: "{{ ansible_devices[bigboot_boot_device[:-1]].partitions[bigboot_boot_device].size }}"

- name: Debug bigboot_boot_partsize
  ansible.builtin.debug:
    var: bigboot_boot_partsize

- name: Capture required expansion space
  ansible.builtin.set_fact:
    bigboot_expansion_diff:
      "{{ bigboot_size | human_to_bytes - bigboot_boot_partsize | human_to_bytes }}"
  no_log: false

- name: Debug bigboot_expansion_diff
  ansible.builtin.debug:
    var: bigboot_expansion_diff

- name: Boo
  ansible.builtin.meta: end_host

- name: Convert size difference to MB
  ansible.builtin.set_fact:
    bigboot_size_expansion_mb: "{{ bigboot_expansion_diff | int | human_readable(unit='M') }}"

- name: Set bigboot size 4k aligned
  ansible.builtin.set_fact:
    bigboot_size_target: "{{ bigboot_size_expansion_mb[:-2] \
      | regex_replace('\\.\\d+ ', '') \
      | int | get_block_size_up }}"

- name: Validate if we need to expand boot
  block:
    - name: Assert that /boot requires expansion
      ansible.builtin.assert:
        that: bigboot_expansion_diff | int <= 0
        fail_msg: The /boot partition will need to be resized
        success_msg: The /boot partition is already at the desired size

    - name: The /boot parition is already at the desired size.
      ansible.builtin.meta: end_host

  rescue:
    - name: Expansion of /boot required
      ansible.builtin.debug:
        msg: "Expanding /boot by an additional {{ bigboot_size_target }}."
