---
- hosts: "{{ host_list }}"
  remote_user: root

  tasks:

    - name: INCLUDE_VARS | base
      ansible.builtin.include_vars: "main.yml"

    - name: INCLUDE_VARS | OS
      ansible.builtin.include_vars: "{{ ansible_distribution }}.yml"

    - name: INCLUDE_VARS | Gnome
      when: "'gnome' in group_names"
      ansible.builtin.include_vars: "Gnome.yml"

    - name: INCLUDE_VARS | Mate
      when: "'mate' in group_names"
      ansible.builtin.include_vars: "Mate.yml"

    - name: Remove snap packages
      when: snap_uninstall_pkg is defined
      community.general.snap:
        name: "{{ snap_uninstall_pkg }}"
        state: absent

    - name: APT | Install base packages
      ansible.builtin.apt:
        cache_valid_time: 3600
        force_apt_get: yes
        pkg: "{{ lookup('flattened', base_pkg) }}"
        state: present
        update_cache: true

    - name: APT | Install OS packages
      ansible.builtin.apt:
        cache_valid_time: 3600
        force_apt_get: yes
        pkg: "{{ lookup('flattened', os_pkg) }}"
        state: present
        update_cache: true

    - name: APT | Install workstation packages
      when: inventory_hostname in groups.station
      ansible.builtin.apt:
        cache_valid_time: 3600
        force_apt_get: yes
        pkg: "{{ lookup('flattened', station_pkg, station_os_pkg, station_wm_pkg) }}"
        state: present
        update_cache: true

    - name: APT | Uninstall packages
      ansible.builtin.apt:
        pkg: "{{ lookup('flattened', base_uninstall_pkg, os_uninstall_pkg) }}"
        state: absent

    - name: APT | Upgrade all packages to the latest version
      ansible.builtin.apt:
        force_apt_get: yes
        upgrade: safe

    - name: APT | Remove useless packages from the cache
      ansible.builtin.apt:
        force_apt_get: yes
        autoclean: yes
        autoremove: yes

    - name: APT | Check for restarts
      ansible.builtin.stat: path={{ item }}
      register: restart_required
      loop:
      - /var/run/firefox-restart-required
      - /var/run/reboot-required
      no_log: yes

    - name: APT | Restart message
      ansible.builtin.debug:
        msg: "{{ item.stat.path | basename }} on {{ ansible_hostname }}"
      when: item.stat.exists
      loop: "{{ restart_required.results }}"
      loop_control:
        label: "{{ item.item | basename }}"
