---
- name: Ensure Megabyte Labs configuration directory exists
  ansible.windows.win_file:
    path: "{{ item }}"
    state: directory
  loop:
    - '%USERPROFILE%\.config'
    - '%USERPROFILE%\.config\megabytelabs'

- name: "Check if {{ app_name }} has configuration stored in '%USERPROFILE%/.config/megabytelabs/ffsend'"
  ansible.windows.win_stat:
    path: '%USERPROFILE%\.config\megabytelabs\ffsend'
  register: ffsend_config

- name: "Detect previously installed {{ app_name }} version"
  ansible.windows.win_shell: type ffsend
  args:
    chdir: '%USERPROFILE%\.config\megabytelabs'
  changed_when: false
  register: current_ffsend_version
  when: ffsend_config.stat.exists

- name: "Detect the latest {{ app_name }} version"
  ansible.windows.win_uri:
    url: https://api.github.com/repos/timvisee/ffsend/releases/latest
    return_content: true
  register: ffsend_latest_release_tag

- name: "Determine whether or not the latest version of {{ app_name }} is already installed"
  set_fact:
    install_ffsend: "{{ (current_ffsend_version.skipped | default(false)) or \
      ((not current_ffsend_version.skipped | default(false)) and \
      (current_ffsend_version.stdout | trim != ffsend_latest_release_tag.json.tag_name | replace('v',''))) }}"

- name: "Ensure {{ ffsend_path }} directory exists"
  ansible.windows.win_file:
    path: "{{ ffsend_path }}"
    state: directory

- name: "Ensure older version of {{ app_name }} is uninstalled"
  ansible.windows.win_file:
    path: "{{ ffsend_path }}/ffsend.exe"
    state: absent
  when: install_ffsend

- name: "Ensure {{ app_name }} is installed"
  ansible.windows.win_get_url:
    url: "{{ 'https://github.com/timvisee/ffsend/releases/download/' + ffsend_latest_release_tag.json.tag_name + \
      '/ffsend-' + ffsend_latest_release_tag.json.tag_name + '-windows-x64-static.exe' }}"
    dest: "{{ ffsend_path }}/ffsend.exe"
  when: install_ffsend

- name: "Ensure {{ app_name }} installation is added to PATH"
  ansible.windows.win_path:
    elements: "{{ ffsend_path }}"
    state: present
  when: install_ffsend

- name: "Save meta information about the version of {{ app_name }} that was installed"
  ansible.windows.win_copy:
    dest: '%USERPROFILE%\.config\megabytelabs\ffsend'
    content: |
      {{ ffsend_latest_release_tag.json.tag_name  | replace('v','') }}
  when: install_ffsend
