---
- 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/agalwood/Motrix/releases/latest
  register: motrix_latest_release_tag

- name: "Determine whether or not the latest version of {{ app_name }} is already installed"
  set_fact:
    install_motrix: "{{ (ansible_local.motrix is not defined) or \
      ((ansible_local.motrix is defined) and \
      (ansible_local['motrix']['settings']['version'] != motrix_latest_release_tag.json.tag_name | replace('v',''))) }}"

- name: "Ensure {{ app_name }} is installed"
  dnf:
    name: "https://github.com/agalwood/Motrix/releases/download/{{ motrix_latest_release_tag.json.tag_name }}/\
      Motrix-{{ motrix_latest_release_tag.json.tag_name | replace('v','') }}.x86_64.rpm"
    state: "{{ app_state | default('present') }}"
  when: install_motrix

- name: "Save meta information about the version of {{ app_name }} that was installed"
  community.general.ini_file:
    path: /etc/ansible/facts.d/motrix.fact
    mode: 0644
    section: settings
    option: version
    value: "{{ motrix_latest_release_tag.json.tag_name | replace('v','') }}"
    backup: true
    no_extra_spaces: true
  when: install_motrix
