# platform = multi_platform_all
# reboot = false
# strategy = configure
# complexity = low
# disruption = low
- name: Gather the package facts
  package_facts:
    manager: auto
  tags:
  - NIST-800-53-AU-5(a)
  - NIST-800-53-AU-5.1(ii)
  - configure_strategy
  - low_complexity
  - low_disruption
  - medium_severity
  - no_reboot_needed
  - postfix_client_configure_mail_alias_postmaster

- name: Configure System to Forward All Mail From Postmaster to The Root Account
  block:

  - name: Check for duplicate values
    ansible.builtin.lineinfile:
      path: /etc/aliases
      create: true
      regexp: (?i)^\s*postmaster\s*:\s*
      state: absent
    check_mode: true
    changed_when: false
    register: dupes

  - name: Deduplicate values from /etc/aliases
    ansible.builtin.lineinfile:
      path: /etc/aliases
      create: true
      regexp: (?i)^\s*postmaster\s*:\s*
      state: absent
    when: dupes.found is defined and dupes.found > 1

  - name: Insert correct line to /etc/aliases
    ansible.builtin.lineinfile:
      path: /etc/aliases
      create: true
      regexp: (?i)^\s*postmaster\s*:\s*
      line: 'postmaster: root'
      state: present
    register: aliases_postmaster_changed
  when: '"linux-base" in ansible_facts.packages'
  tags:
  - NIST-800-53-AU-5(a)
  - NIST-800-53-AU-5.1(ii)
  - configure_strategy
  - low_complexity
  - low_disruption
  - medium_severity
  - no_reboot_needed
  - postfix_client_configure_mail_alias_postmaster

- name: Configure System to Forward All Mail From Postmaster to The Root Account -
    Check if newaliases command is available
  ansible.builtin.stat:
    path: /usr/bin/newaliases
  register: result_newaliases_present
  when: '"linux-base" in ansible_facts.packages'
  tags:
  - NIST-800-53-AU-5(a)
  - NIST-800-53-AU-5.1(ii)
  - configure_strategy
  - low_complexity
  - low_disruption
  - medium_severity
  - no_reboot_needed
  - postfix_client_configure_mail_alias_postmaster

- name: Configure System to Forward All Mail From Postmaster to The Root Account -
    Update postfix aliases
  ansible.builtin.command:
    cmd: newaliases
  when:
  - '"linux-base" in ansible_facts.packages'
  - result_newaliases_present.stat.exists
  - aliases_postmaster_changed is changed
  tags:
  - NIST-800-53-AU-5(a)
  - NIST-800-53-AU-5.1(ii)
  - configure_strategy
  - low_complexity
  - low_disruption
  - medium_severity
  - no_reboot_needed
  - postfix_client_configure_mail_alias_postmaster
