---
# Chatmail relay management — config push + service health checks.
# Initial install is via `cmdeploy run` (out of band); this role manages
# the config, mtail, and verifies services are healthy.

- name: Deploy chatmail.ini
  copy:
    src: "{{ chatmail_config_src }}"
    dest: "{{ chatmail_config_dest }}"
    owner: root
    group: root
    mode: "0644"
  notify:
    - restart postfix
    - restart dovecot
    - restart filtermail
    - restart filtermail-incoming

- name: Ensure mtail is enabled and running
  systemd:
    name: mtail
    enabled: "{{ chatmail_mtail_enabled }}"
    state: started
  when: chatmail_mtail_enabled

- name: Verify core services are running
  command: "systemctl is-active {{ item }}"
  changed_when: false
  loop:
    - postfix
    - dovecot
    - opendkim
    - nginx
    - filtermail
    - filtermail-incoming
    - chatmail-metadata
    - doveauth
  tags: [verify]

- name: Verify SMTP port 25 is listening
  shell: |
    set -euo pipefail
    ss -lntp | grep -E ':25\b' >/dev/null
  args:
    executable: /bin/bash
  changed_when: false
  tags: [verify]

- name: Verify SMTPS port 465 is listening
  shell: |
    set -euo pipefail
    ss -lntp | grep -E ':465\b' >/dev/null
  args:
    executable: /bin/bash
  changed_when: false
  tags: [verify]

- name: Verify submission port 587 is listening
  shell: |
    set -euo pipefail
    ss -lntp | grep -E ':587\b' >/dev/null
  args:
    executable: /bin/bash
  changed_when: false
  tags: [verify]

- name: Verify IMAPS port 993 is listening
  shell: |
    set -euo pipefail
    ss -lntp | grep -E ':993\b' >/dev/null
  args:
    executable: /bin/bash
  changed_when: false
  tags: [verify]

- name: Verify mtail metrics endpoint
  uri:
    url: "http://{{ chatmail_mtail_address }}:{{ chatmail_mtail_port }}/metrics"
    return_content: false
    status_code: 200
  when: chatmail_mtail_enabled
  tags: [verify]
