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

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

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

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

- name: "Ensure {{ app_name }} is downloaded"
  ansible.windows.win_get_url:
    url: "https://get.gravitational.com/teleport-{{ teleport_latest_release_tag.json.tag_name }}-windows-amd64-bin.zip"
    dest: '%TEMP%\teleport.zip'
  when: install_teleport

- name: "Ensure {{ app_name }} is installed"
  community.windows.win_unzip:
    src: '%TEMP%\teleport.zip'
    dest: "%PROGRAMFILES%"
    delete_archive: true
  when: install_teleport

- name: "Ensure {{ app_name }} installation is added to PATH"
  ansible.windows.win_path:
    elements: '%PROGRAMFILES%\teleport'

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