- name: Use rate-mirrors if available
  when: pacman_rate_mirrors
  block:
    - name: Check for rate-mirrors
      ansible.builtin.command: rate-mirrors --version
      register: rate_mirrors_version
      changed_when: false
      failed_when: false

    - name: Run rate-mirrors
      when: rate_mirrors_version.rc == 0
      become: true
      ansible.builtin.shell: |
        . /etc/os-release && rate-mirrors \
            --allow-root \
            --disable-comments \
            --save /etc/pacman.d/mirrorlist \
            "$ID"

- name: Upgrade packages
  become: true
  community.general.pacman:
    update_cache: true
    upgrade: true
  register: pacman_result
  notify: pacman_upgraded

- name: Reboot if necessary
  ansible.builtin.meta: flush_handlers

- name: Install packages
  become: true
  ansible.builtin.package:
    name: '{{ pacman_packages }}'
    state: present
  when: pacman_packages | length > 0