---
- name: Disable swap temporarily and configure permanently
  hosts: all_nodes
  become: true

  tasks:

    - name: Disable swap temporarily
      ansible.builtin.command: swapoff -a
      failed_when: false  # Ignore failure scenarios but capture output for debugging

    - name: Ensure dphys-swapfile is installed
      ansible.builtin.package:
        name: dphys-swapfile
        state: present

    # Gather service facts so we can check for the existence of dphys-swapfile service
    - name: Gather service facts
      ansible.builtin.service_facts:

    - name: Check if /etc/dphys-swapfile exists
      ansible.builtin.stat:
        path: /etc/dphys-swapfile
      register: swapfile_exists

    - name: Stop dphys-swapfile service
      ansible.builtin.service:
        name: dphys-swapfile
        state: stopped
      when: "'dphys-swapfile.service' in ansible_facts.services"

    - name: Set CONF_SWAPSIZE to 0 in /etc/dphys-swapfile
      ansible.builtin.lineinfile:
        path: /etc/dphys-swapfile
        regexp: '^CONF_SWAPSIZE='
        line: 'CONF_SWAPSIZE=0'
      when: swapfile_exists.stat.exists

    - name: Remove existing /var/swap file
      ansible.builtin.file:
        path: /var/swap
        state: absent
      when: swapfile_exists.stat.exists

    - name: Disable dphys-swapfile service
      ansible.builtin.service:
        name: dphys-swapfile
        enabled: no
      when: "'dphys-swapfile.service' in ansible_facts.services"

    - name: Verify swap is turned off
      ansible.builtin.command: free -m
      register: memory_status
      changed_when: false

    - name: Display memory status
      ansible.builtin.debug:
        var: memory_status.stdout_lines

    - name: Reboot the machines to complete swap disabling
      ansible.builtin.reboot:
        reboot_timeout: 1.5  # 2 minutes
        msg: "Rebooting the node to apply permanent swap configuration changes"
        pre_reboot_delay: 5
