---

- name: Ensure Matrix group is created
  group:
    name: "{{ matrix_user_username }}"
    gid: "{{ matrix_user_gid }}"
    state: present

- name: Ensure Matrix user is created
  user:
    name: "{{ matrix_user_username }}"
    uid: "{{ matrix_user_uid }}"
    state: present
    group: "{{ matrix_user_username }}"

- name: Ensure Matrix base path exists
  file:
    path: "{{ item }}"
    state: directory
    mode: "{{ matrix_base_data_path_mode }}"
    owner: "{{ matrix_user_username }}"
    group: "{{ matrix_user_username }}"
  with_items:
    - "{{ matrix_base_data_path }}"

# `docker_network` doesn't work as expected when the given network
# is a substring of a network that already exists.
#
# See:
# - https://github.com/spantaleev/matrix-docker-ansible-deploy/issues/12
# - https://github.com/ansible/ansible/issues/32926
#
# Due to that, we employ a workaround below.
#
# - name: Ensure Matrix network is created in Docker
#   docker_network:
#     name: "{{ matrix_docker_network }}"
#     driver: bridge

- name: Check existence of Matrix network in Docker
  shell:
    cmd: "docker network ls -q --filter='name=^{{ matrix_docker_network }}$'"
  register: result_check_docker_network
  changed_when: false

- name: Create Matrix network in Docker
  shell:
    cmd: "docker network create --driver=bridge {{ matrix_docker_network }}"
  when: "result_check_docker_network.stdout == ''"

- name: Ensure matrix-remove-all script created
  template:
    src: "{{ role_path }}/templates/usr-local-bin/matrix-remove-all.j2"
    dest: "/usr/local/bin/matrix-remove-all"
    mode: 0750