- name: "Ensure Mailu user '{{ mailu_user_key }};{{ mailu_user_name }}@{{ MAILU_DOMAIN }}'' exists"
  command: >
    docker compose exec admin flask mailu {{ mailu_action }}
      {{ mailu_user_name }} {{ MAILU_DOMAIN }} '{{ mailu_password }}'
  args:
    chdir: "{{ MAILU_DOCKER_DIR }}"
  register: mailu_user_result
  failed_when: >
    mailu_user_result.rc != 0 and
    (
      "exists, not created" not in mailu_user_result.stderr and
      "Duplicate entry"   not in mailu_user_result.stderr
    )
  changed_when: mailu_user_result.rc == 0
  when: "'mail-bot' in item.value.roles or 'administrator' in item.value.roles"
  no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}"

- name: "Change password for user '{{ mailu_user_key }};{{ mailu_user_name }}@{{ MAILU_DOMAIN }}'"
  command: >
    docker compose exec admin flask mailu password
      {{ mailu_user_name }} {{ MAILU_DOMAIN }} '{{ mailu_password }}'
  args:
    chdir: "{{ MAILU_DOCKER_DIR }}"
  when: "'mail-bot' in item.value.roles or 'administrator' in item.value.roles"
  no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}"

- name: "Create Mailu API Token for {{ mailu_user_name }}"
  include_tasks: 03_create-token.yml
  when: "{{ 'mail-bot' in item.value.roles }}"