---
- name: Delete existing application if configured to do so
  file:
    path: "/Applications/{{ dmg.name }}.app"
    state: absent
  when: force_reinstall

- name: Download the DMG file to a temporary directory
  get_url:
    url: "{{ dmg.url }}"
    dest: "{{ tmp_dir }}/{{ dmg.name }}.dmg"

- name: Mount the DMG file
  command: "hdiutil attach {{ tmp_dir }}/{{ dmg.name }}.dmg -nobrowse -mountpoint {{ tmp_dir }}/{{ dmg.name }}"
  args:
    creates: "{{ tmp_dir }}/{{ dmg.name }}"

- name: Find the name of the Application folder
  command: find "{{ tmp_dir }}/{{ dmg.name }}" -type d -maxdepth 1 -name '*.app'
  register: app_glob
  changed_when: false

# @action Ensures application is installed
# Installs the application using the DMG file
- name: Copy the application to the Applications folder
  copy:
    src: "{{ app_glob.stdout }}"
    dest: "/Applications/"
    mode: preserve
    owner: root
    remote_src: true

- name: Unmount the DMG file
  command: "hdiutil detach {{ tmp_dir }}/{{ dmg.name }}"
  args:
    removes: "{{ tmp_dir }}/{{ dmg.name }}"

- name: Remove the source DMG file
  file:
    path: "{{ tmp_dir }}/{{ dmg.name }}.dmg"
    state: absent
