---
- name: Ensure Megabyte Labs configuration directory exists
  file:
    mode: 0700
    path: "{{ item }}"
    state: directory
  loop:
    - ~/.config
    - ~/.config/megabytelabs

- name: "Check if {{ app_name }} has configuration stored in ~/.config/megabytelabs/{{ app_name }}"
  stat:
    path: "~/.config/megabytelabs/yq"
  register: yq_config

- name: "Detect previously installed {{ app_name }} version"
  command: cat yq
  args:
    chdir: ~/.config/megabytelabs
  changed_when: false
  register: current_yq_version
  when: yq_config.stat.exists

- name: "Detect the latest {{ app_name }} version"
  uri:
    url: https://api.github.com/repos/mikefarah/yq/releases/latest
  register: yq_latest_release_tag

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

- name: "Ensure older version of {{ app_name }} is uninstalled"
  file:
    path: /usr/local/bin/yq
    state: absent
  when: install_yq

- name: "Ensure {{ app_name }} is installed"
  get_url:
    url: "{{ 'https://github.com/mikefarah/yq/releases/download/' + yq_latest_release_tag.json.tag_name + '/yq_linux_amd64' }}"
    dest: /usr/local/bin/yq
    mode: 0755
  when: install_yq

- name: "Save meta information about the version of {{ app_name }} that was installed"
  copy:
    dest: ~/.config/megabytelabs/yq
    mode: 0600
    content: |
      {{ yq_latest_release_tag.json.tag_name  | replace('v','') }}
  when: install_yq
