---
# Setup swap file on systems without any swap available.
# Must have the swap amount preferred set up in general.ini.
# This does not handle if the user changes the file name or location later on.

- name: General | Software | Swap
  block:

  - name: General | Software | Swap | Check For Swapfile
    stat:
      path: "{{ swap_file }}"
    register: swap_check

  - name: General | Software | Swap | Install Block
    block:

    - name: General | Software | Swap | Create Swapfile
      shell: "{{ item }}"
      loop:
        - dd if=/dev/zero of={{ swap_file }} bs={{ swap_block }}
            count={{ swap_count }} status=progress
        - chmod 600 {{ swap_file }}
        - mkswap {{ swap_file }}
        - swapon {{ swap_file }}

    # Only do the swapfile generation if it does not already exist.
    when: not swap_check.stat.exists

  # NixOS's swap setup is handled in nixos.yml when ansible.nix is created.
  - name: General | Software | Swap | Add to FSTAB
    lineinfile:
      path: /etc/fstab
      regexp: '^[\#]?{{ swap_file }}'
      line: '{{ swap_file }} none swap sw 0 0'
      state: present
      backup: yes
    when: ansible_distribution != "NixOS"

  # Only run through this file if the ini has been changed from false.
  when: swap_block != false