- name: Check if DKIM private key file exists in the antispam container
  command: >
    docker compose exec -T antispam
    test -f {{ MAILU_DKIM_KEY_PATH }}
  register: dkim_key_file_stat
  failed_when:  false
  changed_when: false
  args:
    chdir: "{{ docker_compose.directories.instance }}"

- name: Generate DKIM key
  command: >
    docker compose exec -T antispam
    rspamadm dkim_keygen -s dkim -d {{ MAILU_DOMAIN }} -k {{ MAILU_DKIM_KEY_PATH }}
  register: dkim_keygen_output
  when: dkim_key_file_stat.rc != 0
  args:
    chdir: "{{ docker_compose.directories.instance }}"
  no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}"

- name: Fetch DKIM private key from antispam container
  shell: >
    docker compose exec -T antispam
    cat {{ MAILU_DKIM_KEY_PATH }}
  args:
    chdir: "{{ docker_compose.directories.instance }}"
  register: dkim_priv_content
  failed_when: dkim_priv_content.rc != 0
  changed_when: false
  no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}"

- name: Generate DKIM public key on the host
  command: openssl rsa -pubout
  args:
    stdin: "{{ dkim_priv_content.stdout }}"
  register: dkim_pub_raw
  changed_when: false
  no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}"

- name: Normalize and build Mailu DKIM TXT record
  set_fact:
    mailu_dkim_public_key: >-
      v=DKIM1; k=rsa; p={{
        dkim_pub_raw.stdout
        | regex_replace('-----BEGIN PUBLIC KEY-----', '')
        | regex_replace('-----END PUBLIC KEY-----', '')
        | regex_replace('\s+', '')
      }}
  no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}"

- name: Debug Mailu DKIM public key
  debug:
    msg: "Mailu DKIM public key: {{ mailu_dkim_public_key }}"
  when: MODE_DEBUG | bool
  