---

- ansible.builtin.set_fact:
    matrix_jitsi_prosody_self_check_uvs_health_url: "{{ matrix_jitsi_prosody_auth_matrix_uvs_location }}/health"
    matrix_jitsi_element_jitsi_well_known_url: "{{ matrix_jitsi_web_public_url }}/.well-known/element/jitsi"

- name: Check if jitsi serves the .well-known/element/jitsi
  ansible.builtin.uri:
    url: "{{ matrix_jitsi_element_jitsi_well_known_url }}"
    follow_redirects: none
    return_content: true
    validate_certs: "{{ matrix_jitsi_self_check_validate_certificates }}"
    headers:
      Origin: example.com
  check_mode: false
  register: result_well_known_jitsi_element_jitsi
  ignore_errors: true

- name: Fail if .well-known not working
  ansible.builtin.fail:
    msg: |
      Failed checking that the Jitsi well-known file for Element auth is configured at `{{ matrix_jitsi_element_jitsi_well_known_url }}`
      Full error: {{ result_well_known_jitsi_element_jitsi }}
  when: "result_well_known_jitsi_element_jitsi.failed"

- name: Parse JSON for well-known payload at the matrix hostname
  ansible.builtin.set_fact:
    well_known_matrix_payload: "{{ result_well_known_jitsi_element_jitsi.content | from_json }}"

- name: Fail if .well-known not CORS-aware
  ansible.builtin.fail:
    msg: "The well-known file on `{{ matrix_jitsi_element_jitsi_well_known_url }}` is not CORS-aware. The file needs to be served with an Access-Control-Allow-Origin header set."
  when: "'access_control_allow_origin' not in result_well_known_jitsi_element_jitsi"

- name: Report working .well-known
  ansible.builtin.debug:
    msg: "well-known is configured correctly at `{{ matrix_jitsi_element_jitsi_well_known_url }}`"

- name: Check if we can reach the user verification service and if it's healthy
  ansible.builtin.command:
    argv:
      - "docker"
      - "exec"
      - "matrix-jitsi-prosody"
      - "wget"
      - "-O"
      - "-"
      - "--quiet"
      - "{{ matrix_jitsi_prosody_self_check_uvs_health_url | quote }}"
  register: matrix_jitsi_prosody_self_check_uvs_result
  changed_when: false
  ignore_errors: true

- name: Fail if user verification service is not (reachable and healthy)
  ansible.builtin.fail:
    msg: |
      Failed checking user verification service is up (checked endpoint: `{{ matrix_jitsi_prosody_self_check_uvs_health_url }}`).
      Full error: {{ matrix_jitsi_prosody_self_check_uvs_result }}
  when: "matrix_jitsi_prosody_self_check_uvs_result.failed"

- name: Report healthy user verification service
  ansible.builtin.debug:
    msg: "User verification service is working (checked endpoint: `{{ matrix_jitsi_prosody_self_check_uvs_health_url }}`)"
