---
- name: Register MAS installed apps
  become_user: "{{ ansible_user }}"
  environment:
    PATH: /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:{{ ansible_env.PATH }}
  command: mas list
  register: mas_list
  changed_when: false

- name: Ensure VPN connections are removed if configured to do so
  copy:
    src: "{{ system_connections_path }}"
    dest: "{{ system_connections_path }}.old"
    mode: preserve
  when: remove_vpn_connections | bool

- name: "Ensure {{ app_name }} is installed"
  become_user: "{{ ansible_user }}"
  environment:
    PATH: /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:{{ ansible_env.PATH }}
  shell: |
    mas install {{ wireguard_mas_id }}
  args:
    executable: /bin/bash
    creates: "/Applications/WireGuard.app"
  when: (wireguard_mas_id | string) not in mas_list.stdout

- name: "Ensure {{ app_name }}'s configuration directory exists"
  file:
    path: "{{ wireguard_conf_dir }}"
    state: directory
    mode: 0600

- name: Copy WireGuard connection file
  copy:
    src: "files/vpn/{{ vpn_connection.file }}"
    dest: "{{ wireguard_conf_dir }}/{{ vpn_connection.file | regex_replace('.nmconnection$', '.conf')  }}"
    owner: root
    mode: 0600
  loop: "{{ vpn_connections | default([]) }}"
  loop_control:
    label: "{{ vpn_connection.file }}"
    loop_var: vpn_connection
  when: '"nmconnection" in vpn_connection.file'
