---
# input __postfix_conf - dict of key/value pairs to apply
- name: Apply changes
  when: __postfix_has_config_changed | d("") is search("True")
  block:
    - name: Gather facts for ansible_facts["date_time"]
      setup:
        filter: ansible_date_time
      when: postfix_backup_multiple | bool

    - name: Backup configuration
      copy:
        remote_src: true
        src: /etc/postfix/main.cf
        dest: /etc/postfix/main.cf.{{ postfix_backup_multiple |
          ternary(ansible_facts['date_time']['iso8601'], "backup") }}
        mode: "0644"
      when: postfix_backup or postfix_backup_multiple

    - name: Ensure Last modified header is absent
      lineinfile:
        path: /etc/postfix/main.cf
        regexp: '# Last modified:'
        state: absent

    # Previously, the role inserted a plain-text comment at the top of main.cf.
    # This task removes this outdated header for compatibility.
    - name: Ensure the outdated ansible managed header is absent
      lineinfile:
        path: /etc/postfix/main.cf
        regexp: "# This file is managed by [aA]nsible"
        state: absent

    - name: Ensure ansible_managed header in configuration file
      vars:
        __lsr_ansible_managed: "{{
          lookup('template', 'get_ansible_managed.j2') }}"
      blockinfile:
        path: /etc/postfix/main.cf
        block: "{{ __lsr_ansible_managed }}"
        insertbefore: BOF

    - name: Configure Postfix
      command: postconf -e {{ item.key | quote }}={{ item.value | quote }}
      notify:
        - Check postfix
        - Restart postfix
      with_dict: "{{ __postfix_conf }}"
      when:
        - item.key not in ['previous']
        - __postfix_has_config_changed
          | d("") is search("True itemstr " ~ item.key)
      changed_when:
        - item.key not in ['previous']
        - __postfix_has_config_changed
          | d("") is search("True itemstr " ~ item.key)
