---
- name: "Ensure {{ app_name }}'s dependencies are installed"
  become_method: runas
  become_user: "{{ ansible_user }}"
  chocolatey.chocolatey.win_chocolatey:
    name:
      - winpcap
      - mingw
    state: "{{ app_state | default('present') }}"

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

- name: "Detect previously installed {{ app_name }} version"
  ansible.windows.win_command: cat bandwhich
  args:
    chdir: '%USERPROFILE%\.config\megabytelabs'
  changed_when: false
  register: current_bandwhich_version
  when: bandwhich_config.stat.exists

- name: "Detect the latest {{ app_name }} version"
  ansible.windows.win_uri:
    url: https://api.github.com/repos/imsnif/bandwhich/releases/latest
  register: bandwhich_latest_release_tag

- name: "Determine whether or not the latest version of {{ app_name }} is already installed"
  set_fact:
    install_bandwhich: "{{ (current_bandwhich_version.skipped) or \
      ((not current_bandwhich_version.skipped) and (current_bandwhich_version.stdout != bandwhich_latest_release_tag.json.tag_name)) }}"

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

- name: "Ensure {{ app_name }} is installed"
  ansible.windows.win_shell: |
    cargo install bandwhich --root "C:\Program Files\bandwhich"
  args:
    creates: '%PROGRAMFILES%\bandwhich\bandwhich'
  when: install_bandwhich

- name: "Save meta information about the version of {{ app_name }} that was installed"
  ansible.windows.win_copy:
    dest: '%USERPROFILE%\.config\megabytelabs\bandwhich'
    content: |
      {{ bandwhich_latest_release_tag.json.tag_name }}
  when: install_bandwhich
