# platform = multi_platform_all
# reboot = false
# strategy = restrict
# complexity = low
# disruption = low
- name: Gather the package facts
  package_facts:
    manager: auto
  tags:
  - low_complexity
  - low_disruption
  - medium_severity
  - no_reboot_needed
  - postfix_prevent_unrestricted_relay
  - restrict_strategy

- name: Prevent Unrestricted Mail Relaying
  block:

  - name: Check for duplicate values
    ansible.builtin.lineinfile:
      path: /etc/postfix/main.cf
      create: true
      regexp: (?i)^[ \t]*smtpd_client_restrictions\s*=\s*
      state: absent
    check_mode: true
    changed_when: false
    register: dupes

  - name: Deduplicate values from /etc/postfix/main.cf
    ansible.builtin.lineinfile:
      path: /etc/postfix/main.cf
      create: true
      regexp: (?i)^[ \t]*smtpd_client_restrictions\s*=\s*
      state: absent
    when: dupes.found is defined and dupes.found > 1

  - name: Insert correct line to /etc/postfix/main.cf
    ansible.builtin.lineinfile:
      path: /etc/postfix/main.cf
      create: true
      regexp: (?i)^[ \t]*smtpd_client_restrictions\s*=\s*
      line: smtpd_client_restrictions = permit_mynetworks,reject
      state: present
  when:
  - '"linux-base" in ansible_facts.packages'
  - '"postfix" in ansible_facts.packages'
  tags:
  - low_complexity
  - low_disruption
  - medium_severity
  - no_reboot_needed
  - postfix_prevent_unrestricted_relay
  - restrict_strategy
