---
- 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/goofys"
  stat:
    path: ~/.config/megabytelabs/goofys
  register: goofys_config

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

- name: "Detect the latest {{ app_name }} version"
  uri:
    url: https://api.github.com/repos/kahing/goofys/releases/latest
  register: goofys_latest_release_tag

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

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

- name: "Ensure {{ app_name }} is installed"
  get_url:
    url: "https://github.com/kahing/goofys/releases/download/{{ goofys_latest_release_tag.json.tag_name }}/goofys"
    dest: /usr/local/bin/goofys
    mode: 0755
  when: install_goofys

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