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

- name: "Ensure installation folder for {{ app_name }} exists"
  ansible.windows.win_file:
    path: "{{ pup_src_dir }}"
    state: directory

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

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

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

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

- name: "Find the Checksum of {{ app_name }} installer"
  set_fact:
    pup_checksum: "{{ pup_latest_release_tag.json.body | regex_search('.*pup_v(\\d\\.)*\\d*_windows_amd64.zip') | \
      regex_replace('  pup_v(\\d\\.)*\\d*_windows_amd64.zip','') }}"
  when: install_pup

- name: "Acquire {{ app_name }}'s latest installer"
  ansible.windows.win_get_url:
    url: "https://github.com/ericchiang/pup/releases/download/{{ pup_latest_release_tag.json.tag_name }}/\
      pup_{{ pup_latest_release_tag.json.tag_name }}_windows_amd64.zip"
    dest: "{{ pup_src_dir }}/pup_{{ pup_latest_release_tag.json.tag_name }}_windows_amd64.zip"
    checksum: "{{ pup_checksum }}"
    checksum_algorithm: sha256
  when: install_pup

- name: "Ensure {{ app_name }} is installed"
  community.windows.win_unzip:
    src: "{{ pup_src_dir }}/pup_{{ pup_latest_release_tag.json.tag_name }}_windows_amd64.zip"
    dest: "{{ pup_src_dir }}"
    delete_archive: true
  when: install_pup

- name: "Add {{ pup_src_dir }} to PATH"
  ansible.windows.win_path:
    elements: "{{ pup_src_dir }}"
    state: present

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