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

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

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

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

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

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

- name: "Ensure {{ app_name }} is installed"
  ansible.windows.win_get_url:
    url: "https://dystroy.org/broot/download/x86_64-pc-windows-gnu/broot.exe"
    dest: "{{ broot_dest_dir }}\\broot.exe"
  when: install_broot

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

- name: "Ensure {{ app_name }}'s completion is installed"
  ansible.windows.win_get_url:
    url: "https://dystroy.org/broot/download/completion/_broot.ps1"
    dest: "{{ broot_dest_dir }}\\_broot.ps1"
  when: install_broot

- name: Configure initialization script for PowerShell
  become_method: runas
  become_user: "{{ user.username }}"
  community.windows.win_lineinfile:
    path: '%USERPROFILE%\Documents\PowerShell\Microsoft.PowerShell_profile.ps1'
    line: '. $env:PROGRAMFILES\broot\_broot.ps1'
  loop: "{{ user_configs }}"
  loop_control:
    label: "{{ user.username }}"
    loop_var: user
  when:
    - install_broot
    - (user.system is not defined) or ((user.system is defined) and (not user.system))

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