---
- name: Perform logical volume and boot parition resizing as needed
  hosts: all
  become: true
  gather_facts: true
  strategy: free

  vars_files:
    - bigboot_vars.yml

  tasks:
    - name: Perform filesystem check prior to Bigboot execution
      ansible.builtin.import_tasks: tasks/grub_filesystem_check.yml
      when:
        - bigboot_data[inventory_hostname]['bigboot_execute_bigboot'] | default(false) | bool

    - name: Shrink the logical volume to support /boot expansion
      ansible.builtin.import_role:
        name: infra.lvm_snapshots.shrink_lv
      vars:
        shrink_lv_devices:
          - device: "{{ bigboot_data[inventory_hostname]['bigboot_adjacent_lvm_device'] }}"
            size: "{{ bigboot_data[inventory_hostname]['bigboot_lv_shrink_size'] | int }}"
      when:
        - bigboot_data[inventory_hostname]['bigboot_execute_shrink_lv'] | default(false) | bool

    - name: Shift free extents and expand /boot
      when:
        - bigboot_data[inventory_hostname]['bigboot_execute_bigboot'] | bool
      block:
        # Under normal circumstances we'd use this method, but unable to do
        # so in certain environments so lets use copy/command instead
        # - name: Shift free extents to end of PV
        #   ansible.builtin.script: "scripts/pvsqueeze.sh {{ bigboot_data[inventory_hostname]['bigboot_pv'] }}"
        #   register: bigboot_pvsqueeze

        - name: Copy pvsqueeze.sh script to host
          ansible.builtin.copy:
            src: scripts/pvsqueeze.sh
            dest: /var/tmp/pvsqueeze.sh
            owner: root
            group: root
            mode: '0700'

        - name: Shift free extents to end of PV
          ansible.builtin.command:
            cmd: "/var/tmp/pvsqueeze.sh {{ bigboot_data[inventory_hostname]['bigboot_pv'] }}"
          register: bigboot_pvsqueeze

        - name: Remove pvsqueeze.sh from host
          ansible.builtin.file:
            path: /var/tmp/pvsqueeze.sh
            state: absent

        - name: Expand the /boot partition as requested
          ansible.builtin.import_role:
            name: infra.lvm_snapshots.bigboot
          vars:
            bigboot_partition_size: "{{ bigboot_size_target }}"

        - name: Failure on request
          ansible.builtin.fail:
            msg: "Ansible job has been failed upon request."
          when:
            - bigboot_fail_request | default(false) | bool

      rescue:
        - name: Cleanup from any previous executions
          ansible.builtin.import_tasks: tasks/cleanup.yml
