---
- name: "load docker, db and proxy for {{ application_id }}"
  include_role: 
    name: cmp-db-docker-proxy
  vars:
    proxy_extra_configuration: >-
      {% if not applications | get_app_conf(application_id, 'public_api_activated', True) %}
      {{ lookup('file', '{{ playbook_dir }}/roles/web-app-listmonk/files/deactivate-public-api.conf') }}
      {% else %}
      ""
      {% endif %}

- name: add config.toml
  template: 
    src:  "config.toml.j2" 
    dest: "{{docker_compose.directories.config}}config.toml"
  notify: docker compose up

- meta: flush_handlers

- name: Check if listmonk database is already initialized
  command: docker compose exec -T {{ database_host }} psql -U {{ database_username }} -d {{ database_name }} -c "\dt"
  register: db_tables
  changed_when: false
  failed_when: false

- name: Run Listmonk setup only if DB is empty
  command:
    cmd: docker compose run -T --rm application sh -c "yes | ./listmonk --install"
    chdir: "{{ docker_compose.directories.instance }}"
  when: "'No relations found.' in db_tables.stdout"

- name: Build OIDC settings JSON
  set_fact:
    oidc_settings_json: >-
      {{ {
         "enabled":       True,
         "client_id":     OIDC.CLIENT.ID,
         "provider_url":  OIDC.CLIENT.ISSUER_URL,
         "client_secret": OIDC.CLIENT.SECRET
      } | to_json }}

- name: Update administrator email and password login in Listmonk
  shell: |
    docker exec -i {{ database_host }} psql \
      -U {{ database_username }} \
      -v ON_ERROR_STOP=1 \
      -d {{ database_name }} << 'EOSQL'
    UPDATE users
    SET email = '{{ users.administrator.email }}',
        password_login = {{ 'false' if applications | get_app_conf(application_id, 'features.oidc', True) else 'true' }}
    WHERE username = 'administrator';
    EOSQL
  args:
    executable: /bin/bash

- name: Apply all Listmonk settings
  shell: |
    docker exec -i {{ database_host }} psql \
      -U {{ database_username }} \
      -v ON_ERROR_STOP=1 \
      -d {{ database_name }} << 'EOSQL'
    UPDATE settings
    SET value = '{{ item.value }}'::jsonb
    WHERE key = '{{ item.key }}';
    EOSQL
  args:
    executable: /bin/bash
  loop: "{{ LISTMONK_SETTINGS }}"
  loop_control:
    label: "{{ item.key }}"
  when: item.when is not defined or item.when
  no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}"
  async: "{{ ASYNC_TIME if ASYNC_ENABLED | bool else omit }}"
  poll:  "{{ ASYNC_POLL if ASYNC_ENABLED | bool else omit }}"
