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

- name: "Ensure '%PROGRAMFILES%/wp-cli' exists"
  ansible.windows.win_file:
    path: '%PROGRAMFILES%\wp-cli'
    state: directory

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

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

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

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

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

- name: "Ensure {{ app_name }} is installed"
  ansible.windows.win_get_url:
    url: "{{ 'https://github.com/wp-cli/wp-cli/releases/download/' + wpcli_latest_release_tag.json.tag_name + \
      '/wp-cli-' + wpcli_latest_release_tag.json.tag_name | replace('v','') + '.phar' }}"
    dest: '%PROGRAMFILES%\wp-cli\wp-cli.phar'
  when: install_wpcli

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

- name: "Ensure wp.bat is present"
  ansible.windows.win_copy:
    dest: '%PROGRAMFILES%\wp-cli\wp.bat'
    content: |
      @ECHO OFF
      php "c:/Program Files/wp-cli/wp-cli.phar" %*

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