---
- name: Install postfix and SASL auth library
  ansible.builtin.dnf:
    name:
      - postfix
      - cyrus-sasl-plain
      - s-nail
    state: present

- name: Deploy main.cf
  ansible.builtin.template:
    src: main.cf.j2
    dest: /etc/postfix/main.cf
    owner: root
    group: root
    mode: '0644'
  notify: Restart postfix

- name: Deploy sasl_passwd
  ansible.builtin.template:
    src: sasl_passwd.j2
    dest: /etc/postfix/sasl_passwd
    owner: root
    group: root
    mode: '0600'
  register: sasl_passwd_result

- name: Run postmap on sasl_passwd
  ansible.builtin.command: postmap /etc/postfix/sasl_passwd
  when: sasl_passwd_result.changed
  changed_when: true
  notify: Restart postfix

- name: Deploy generic sender rewrite map
  ansible.builtin.copy:
    dest: /etc/postfix/generic
    content: |
      # Réécriture expéditeur — géré par Ansible
      @{{ postfix_myhostname }}  {{ postfix_sender_email }}
      root                       {{ postfix_sender_email }}
    owner: root
    group: root
    mode: '0644'
  register: generic_map_result
  when: postfix_sender_email | length > 0

- name: Run postmap on generic map
  ansible.builtin.command: postmap /etc/postfix/generic
  when: generic_map_result is changed
  changed_when: true
  notify: Restart postfix

- name: Reset postfix failed state if any
  ansible.builtin.command: systemctl reset-failed postfix.service
  changed_when: false
  failed_when: false

- name: Enable and start postfix
  ansible.builtin.systemd:
    name: postfix
    enabled: true
    state: started
    daemon_reload: true

- name: Open port 25 from cluster LAN in nftables
  ansible.builtin.lineinfile:
    path: /etc/nftables.conf
    insertafter: '# alertmanager-webhook'
    line: "    tcp dport 25 ip saddr 192.168.10.0/24 accept comment \"postfix-relay\""
    state: present
  when: postfix_open_nftables
  notify: Reload nftables
