---

- name: Install and configure Flatpak
  tags:
    - flatpak
    - package_manager
    - package_managers
    - package-manager
    - package-managers
    - pkg_mgr
  hosts: all
  vars:
    flathub_enabled: true
    flathub_method: user
    flathub_name: flathub
    flathub_url: https://flathub.org/repo/flathub.flatpakrepo
    remotes: []
  tasks:
    - name: Install and configure Flatpak on Linux systems
      when: ansible_system == 'Linux'
      tags: linux
      block:
        - name: Install flatpak
          tags:
            - install
            - installation
          become: true
          ansible.builtin.package:
            name: flatpak
            state: present
        - name: Configure Flatpak
          tags:
            - configure
            - configuration
          block:
            - name: Add flathub to the list of remotes of this run
              when: flathub_enabled
              ansible.builtin.set_fact:
                remotes: "{{ remotes + [{'name': flathub_name, 'method': flathub_method, 'url': flathub_url}] }}"
            - name: Enable system remotes
              tags:
                - remote
                - remotes
                - system
              when: item.method == 'system'
              become: true
              community.general.flatpak_remote:
                name: "{{ item.name }}"
                flatpakrepo_url: "{{ item.url }}"
              loop: "{{ remotes }}"
            - name: Enable user remotes
              tags:
                - remote
                - remotes
                - user
              when: item.method == 'user'
              community.general.flatpak_remote:
                name: "{{ item.name }}"
                flatpakrepo_url: "{{ item.url }}"
                method: user
              loop: "{{ remotes }}"
