---
- 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/shfmt'"
  ansible.windows.win_stat:
    path: '%USERPROFILE%\.config\megabytelabs\shfmt'
  register: shfmt_config

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

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

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

- name: Ensure installation folder exists
  ansible.windows.win_file:
    path: '%PROGRAMFILES%\shfmt\'
    state: directory

- name: "Ensure older version of {{ app_name }} is uninstalled"
  ansible.windows.win_file:
    path: '%PROGRAMFILES%\shfmt\shfmt.exe'
    state: absent
  when: install_shfmt

- name: "Ensure {{ app_name }} is installed"
  ansible.windows.win_get_url:
    url: "{{ 'https://github.com/mvdan/sh/releases/download/' + shfmt_latest_release_tag.json.tag_name + '/shfmt_' \
      + shfmt_latest_release_tag.json.tag_name + '_windows_amd64.exe' }}"
    dest: '%PROGRAMFILES%\shfmt\shfmt.exe'
  when: install_shfmt

- name: "Add new {{ app_name }} PATH"
  win_path:
    elements: '%PROGRAMFILES%\shfmt\'
    state: present

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