---
- name: "Ensure {{ app_name }} is installed"
  dnf:
    name: bat
    state: present
  when: ansible_distribution == 'Fedora'

- name: "Ensure {{ app_name }} is installed"
  block:
    - name: Ensure custom facts directory exists
      file:
        mode: 0755
        path: /etc/ansible/facts.d
        state: directory
    - name: "Detect the latest {{ app_name }} version"
      uri:
        url: https://api.github.com/repos/sharkdp/bat/releases/latest
      register: bat_latest_release_tag
    - name: "Determine whether or not the latest version of {{ app_name }} is already installed"
      set_fact:
        install_bat: "{{ (ansible_local.bat is not defined) or \
          ((ansible_local.bat is defined) and \
          (ansible_local['bat']['settings']['version'] != bat_latest_release_tag.json.tag_name | replace('v',''))) }}"
    - name: "Ensure {{ app_name }} is installed"
      unarchive:
        src: "https://github.com/sharkdp/bat/releases/download/{{ bat_latest_release_tag.json.tag_name }}/\
          bat-{{ bat_latest_release_tag.json.tag_name }}-x86_64-unknown-linux-musl.tar.gz"
        dest: /usr/local/bin
        extra_opts:
          - --strip-components=1
        exclude:
          - CHANGELOG.md
          - LICENSE-APACHE
          - LICENSE-MIT
          - README.md
          - bat.1
          - autocomplete
        remote_src: true
      when: install_bat
    - name: "Save meta information about the version of {{ app_name }} that was installed"
      community.general.ini_file:
        path: /etc/ansible/facts.d/bat.fact
        mode: 0644
        section: settings
        option: version
        value: "{{ bat_latest_release_tag.json.tag_name | replace('v','') }}"
        backup: true
        no_extra_spaces: true
      when: install_bat
  when: ansible_distribution != 'Fedora'
