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

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

- name: "Detect the latest {{ app_name }} version"
  uri:
    url: https://releases.hashicorp.com/nomad/
    return_content: true
  register: nomad_releases

- name: "Save the latest version of {{ app_name }} to a variable"
  set_fact:
    nomad_latest_release_version: "{{ nomad_releases.content | regex_search('_(((\\d)*\\.)*\\d*)') | replace ('_','') }}"

- name: "Determine whether or not the latest version of {{ app_name }} is already installed"
  set_fact:
    install_nomad: "{{ (current_nomad_version.skipped) or \
      ((not current_nomad_version.skipped) and (current_nomad_version.stdout != nomad_latest_release_version)) }}"

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

- name: "Ensure {{ app_name }} is installed"
  unarchive:
    src: "{{ 'https://releases.hashicorp.com/nomad/' + nomad_latest_release_version + '/nomad_' + nomad_latest_release_version + '_linux_amd64.zip' }}"
    dest: /usr/local/bin
    remote_src: true
  when: install_nomad

- name: "Save meta information about the version of {{ app_name }} that was installed"
  copy:
    dest: ~/.config/megabytelabs/nomad
    mode: 0600
    content: |
      {{ nomad_latest_release_version }}
  when: install_nomad
