---
- name: "Ensure {{ app_name }} is installed"
  apt:
    name: bat
    state: "{{ app_state | default('present') }}"
    update_cache: "{{ omit if skip_package_cache_update is defined else 'true' }}"
  when: (ansible_distribution == 'Ubuntu' or ansible_distribution_major_version > 10)

- 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"
      apt:
        name: "https://github.com/sharkdp/bat/releases/download/{{ bat_latest_release_tag.json.tag_name }}/\
          bat-musl_{{ bat_latest_release_tag.json.tag_name | replace('v','') }}_amd64.deb"
        state: "{{ app_state | default('present') }}"
      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 == 'Debian'
    - ansible_distribution_major_version == 10
