- name: Ensure snapd is installed
  ansible.builtin.package:
    name: snapd
    state: present
  become: true

- name: Ensure snapd service is enabled and started
  ansible.builtin.systemd:
    name: snapd
    state: started
    enabled: true
  become: true

- name: Get list of installed Snaps
  ansible.builtin.command: snap list
  register: installed_snaps
  changed_when: false

- name: Define protected system snaps
  ansible.builtin.set_fact:
    system_snaps:
      - snapd
      - core
      - core18
      - core20
      - core22
      - bare
      - gtk-common-themes
      - gnome-3-28-1804
      - gnome-3-34-1804
      - gnome-3-38-2004
      - gnome-42-2204
      - desktop-security-center
      - firmware-updater
      - prompting-client
      - snap-store
      - snapd-desktop-integration

- name: Define desired Snaps
  ansible.builtin.set_fact:
    desired_snaps:
      - name: firefox
        classic: false
      - name: bitwarden
        classic: false
      - name: bw
        classic: false

- name: Install desired Snap packages
  ansible.builtin.command: "snap install {{ item.name }} {{ '--classic' if item.classic else '' }}"
  loop: "{{ desired_snaps }}"
  become: true
  register: snap_install
  changed_when: "'already installed' not in snap_install.stderr"
  failed_when:
    - snap_install.rc != 0
    - "'already installed' not in snap_install.stderr"

- name: Remove undesired Snap packages
  ansible.builtin.command: "snap remove {{ item }}"
  become: true
  loop: >-
    {{
      installed_snaps.stdout_lines[1:]
      | map('split', ' ')
      | map('first')
      | difference(desired_snaps | map(attribute='name'))
      | difference(system_snaps)
    }}
  register: snap_remove
  changed_when: snap_remove.rc == 0
  failed_when:
    - snap_remove.rc != 0
    - "'not installed' not in snap_remove.stderr"
    - "'cannot remove' not in snap_remove.stderr"
