# SPDX-FileCopyrightText: 2022 MDAD project contributors
# SPDX-FileCopyrightText: 2024 wjbeckett
# SPDX-FileCopyrightText: 2024 - 2025 Slavi Pantaleev
#
# SPDX-License-Identifier: AGPL-3.0-or-later

---

- name: Ensure Element Call paths exist
  ansible.builtin.file:
    path: "{{ item.path }}"
    state: directory
    mode: '0750'
    owner: "{{ matrix_user_name }}"
    group: "{{ matrix_group_name }}"
  with_items:
    - path: "{{ matrix_element_call_base_path }}"

- name: Ensure Element Call config.json is in place
  ansible.builtin.template:
    src: "{{ role_path }}/templates/config.json.j2"
    dest: "{{ matrix_element_call_base_path }}/config.json"
    mode: '0640'
    owner: "{{ matrix_user_name }}"
    group: "{{ matrix_group_name }}"
  register: matrix_element_call_config_result

- name: Ensure Element Call container labels file is in place
  ansible.builtin.template:
    src: "{{ role_path }}/templates/labels.j2"
    dest: "{{ matrix_element_call_base_path }}/labels"
    mode: '0640'
    owner: "{{ matrix_user_name }}"
    group: "{{ matrix_group_name }}"
  register: matrix_element_call_support_files_result

- name: Ensure Element Call container image is pulled
  community.docker.docker_image:
    name: "{{ matrix_element_call_container_image }}"
    source: pull
    force_source: "{{ matrix_element_call_container_image_force_pull }}"
  register: matrix_element_call_container_image_pull_result
  retries: "{{ devture_playbook_help_container_retries_count }}"
  delay: "{{ devture_playbook_help_container_retries_delay }}"
  until: matrix_element_call_container_image_pull_result is not failed

- name: Ensure Element Call container network is created
  community.general.docker_network:
    enable_ipv6: "{{ devture_systemd_docker_base_ipv6_enabled }}"
    name: "{{ matrix_element_call_container_network }}"
    driver: bridge
    driver_options: "{{ devture_systemd_docker_base_container_networks_driver_options }}"

- name: Ensure Element Call systemd service is installed
  ansible.builtin.template:
    src: "{{ role_path }}/templates/systemd/matrix-element-call.service.j2"
    dest: "{{ devture_systemd_docker_base_systemd_path }}/matrix-element-call.service"
    mode: '0644'
  register: matrix_element_call_systemd_service_result

- name: Determine whether Element Call needs a restart
  ansible.builtin.set_fact:
    matrix_element_call_restart_necessary: >-
      {{
        matrix_element_call_config_result.changed | default(false)
        or matrix_element_call_support_files_result.changed | default(false)
        or matrix_element_call_systemd_service_result.changed | default(false)
        or matrix_element_call_container_image_pull_result.changed | default(false)
      }}
