- name: Check if Flatpak is installed
  ansible.builtin.command: which flatpak
  register: flatpak_check
  changed_when: false
  failed_when: false

- name: Install Flatpak
  ansible.builtin.package:
    name: flatpak
    state: present
  become: true
  when: flatpak_check.rc != 0

- name: Add Flathub remote repository
  community.general.flatpak_remote:
    name: flathub
    flatpakrepo_url: https://dl.flathub.org/repo/flathub.flatpakrepo
    state: present

- name: Get list of system installed Flatpaks
  ansible.builtin.command: flatpak list --system --app --columns=application
  register: installed_system_flatpaks
  changed_when: false

- name: Get list of system remotes
  ansible.builtin.command: flatpak remote-list --system --columns=name
  register: system_remotes
  changed_when: false

- name: Define system desired Flatpaks
  ansible.builtin.set_fact:
    desired_system_flatpaks:
      - org.fkoehler.KTailctl
      - com.spotify.Client
      - org.gnome.Extensions
      - io.github.openhv.OpenHV
      - com.usebottles.bottles
      - io.github.shiftey.Desktop
      - com.github.tchx84.Flatseal
      - com.github.wwmm.easyeffects
      - dev.bragefuglseth.Keypunch
      - org.onlyoffice.desktopeditors
      - io.gitlab.adhami3310.Impression
      - org.prismlauncher.PrismLauncher
      - io.ente.auth
      - io.github.fastrizwaan.WineZGUI
      - net.davidotek.pupgui2
      - tv.plex.PlexDesktop
      - com.mastermindzh.tidal-hifi
      - io.github.flattool.Warehouse
      - net.lutris.Lutris
      - com.plexamp.Plexamp
      - io.github.nokse22.Exhibit
      - net.nokyan.Resources
      - dev.zed.Zed
      - page.tesk.Refine
      - io.github.flattool.Ignition
      - io.github.bytezz.IPLookup
      - io.github.giantpinkrobots.varia
      - io.bassi.Amberol
      - org.gaphor.Gaphor
      - io.github.seadve.Mousai
      - info.beyondallreason.bar
      - com.jeffser.Alpaca

- name: Define system desired Flatpak remotes
  ansible.builtin.set_fact:
    desired_system_flatpak_remotes:
      - flathub

- name: Add desired system Flatpak remotes
  community.general.flatpak_remote:
    name: "{{ item }}"
    state: present
    method: system
  loop: "{{ desired_system_flatpak_remotes }}"

- name: Remove undesired system Flatpak remotes
  community.general.flatpak_remote:
    name: "{{ item }}"
    state: absent
    method: system
  loop: "{{ system_remotes.stdout_lines | difference(desired_system_flatpak_remotes) }}"

- name: Install/Upgrade Flatpak packages
  community.general.flatpak:
    name: "{{ item }}"
    state: present
    method: system
  loop: "{{ desired_system_flatpaks }}"

- name: Remove undesired system Flatpaks
  community.general.flatpak:
    name: "{{ item }}"
    state: absent
    method: system
  loop: "{{ installed_system_flatpaks.stdout_lines | difference(desired_system_flatpaks) }}"
