---

- hosts: all

  tasks:

  - name: Check if file '/etc/postfix/main.cf' exists
    stat:
      path: /etc/postfix/main.cf
    register: postfix_main_cf_exists

  # ---
  # /etc/postfix/main.cf: compatibility_level = 2
  # ---

  - name: Check if String 'compatibility_level =..' is present
    shell: grep -q -E "^\s*compatibility_level\s*=" /etc/postfix/main.cf
    register: compatibility_level_present
    when: postfix_main_cf_exists.stat.exists
    failed_when: "compatibility_level_present.rc > 1"
    changed_when: "compatibility_level_present.rc > 0"

  - name: Adjust file '/etc/postfix/main.cf' (compatibility_level)
    blockinfile:
      path: /etc/postfix/main.cf
      insertafter: '^#\s*=+\s*Basic\s*settings\s*=+'
      block: |
        # Disable backwards compatibility
        #
        compatibility_level = 2

      marker: "# Marker set by modify-postfix-main-dot-cf.yml (compatibility_level)"
    when: 
      - postfix_main_cf_exists.stat.exists
      - compatibility_level_present is changed
    notify:
      - Restart postfix


  # ---
  # Remove Marker set by blockinfile
  # ---

  - name: Remove marker
    replace :
      path: /etc/postfix/main.cf
      regexp: "^# Marker set by modify-postfix-main-dot-cf.yml.*$"
      replace: ""
    #register: marker_ipv4_removed
    #failed_when: "marker_ipv4_removed.rc > 1"
    #changed_when: "marker_ipv4_removed.rc < 1"
    when:
      - postfix_main_cf_exists.stat.exists



  # ===
  # Handlers used by this playbook
  # ===

  handlers:

    - name: Restart postfix
      service:
        name: postfix
        state: restarted
