# Load this role via nginx-modifier-all for consistency

- name: "Relevant variables for role: {{ role_path | basename }}"
  debug:
    msg:
      domain: "{{ domain }}"
      base_domain: "{{ base_domain }}"
      verification_url: "{{ verification_url }}"
  when: enable_debug | bool

- name: "Check if site {{ domain }} is allready registered at Matomo"
  uri:
    url:            "{{verification_url}}"
    method:         GET
    return_content: yes
    status_code:    200
    validate_certs: yes
  register:         site_check

- name: Set matomo_site_id to Null
  set_fact:
    matomo_site_id: Null

- name: Set fact for site ID if site already exists
  set_fact:
    matomo_site_id: "{{ site_check.json[0].idsite }}"
  when: "(site_check.json | length) > 0"
  changed_when: false

- name: Add site to Matomo and get ID if not exists
  uri:
    url: "{{ web_protocol }}://{{ domains.matomo }}/index.php"
    method: POST
    body: "module=API&method=SitesManager.addSite&siteName={{ base_domain }}&urls=https://{{ base_domain }}&token_auth={{ applications.matomo.credentials.auth_token }}&format=json"
    body_format: form-urlencoded
    status_code: 200
    return_content: yes
    validate_certs: yes
  register: add_site
  when: "matomo_site_id is not defined or matomo_site_id is none"

- name: Set fact for site ID if site was added
  set_fact:
    matomo_site_id: "{{ add_site.json.value }}"
  when: "matomo_site_id is not defined or matomo_site_id is none"
  changed_when: false

- name: Set the Matomo tracking code from a template file
  set_fact:
    matomo_tracking_code: "{{ lookup('template', 'matomo-tracking.js.j2') }}"

- name: Set the tracking code as a one-liner
  set_fact:
    matomo_tracking_code_one_liner: "{{ matomo_tracking_code | regex_replace('\\n', '') | regex_replace('\\s+', ' ') }}"

- name: Ensure csp.hashes exists for this app
  set_fact:
    applications: >-
      {{
        applications
        | combine({
            (application_id): {
              'csp': {
                'hashes': {}
              }
            }
          }, recursive=True)
      }}
  changed_when: false

- name: Append Matomo one-liner to script-src inline hashes
  set_fact:
    applications: >-
      {{
        applications
        | combine({
            (application_id): {
              'csp': {
                'hashes': {
                  'script-src': (
                    applications[application_id]['csp']['hashes'].get('script-src', [])
                    + [ matomo_tracking_code_one_liner ]
                  )
                }
              }
            }
          }, recursive=True)
      }}
  changed_when: false
