# SPDX-License-Identifier: MIT
---
- name: Test installation and configuration of Postfix agent
  hosts: all
  vars:
    metrics_from_postfix: true

  pre_tasks:
    - name: Stop test
      meta: end_host
      when: (ansible_distribution in ['RedHat', 'CentOS'] and ansible_distribution_major_version | int < 7) or ansible_distribution not in ['Fedora', 'RedHat', 'CentOS']

    - name: Save state of services
      import_tasks: get_services_state.yml

    - name: Determine if system is ostree and set flag
      when: not __ansible_pcp_is_ostree is defined
      block:
        - name: Check if system is ostree
          stat:
            path: /run/ostree-booted
          register: __ostree_booted_stat

        - name: Set flag to indicate system is ostree
          set_fact:
            __ansible_pcp_is_ostree: "{{ __ostree_booted_stat.stat.exists }}"

    - name: Ensure Postfix is installed
      package:
        name:
          - postfix
          - postfix-perl-scripts
        state: present
        use: "{{ (__ansible_pcp_is_ostree | d(false)) | ternary('ansible.posix.rhel_rpm_ostree', omit) }}"

  # needed for older versions of PCP which mandated a log file
  # exists in order that the PMDA would start up at all.
    - name: Ensure a Postfix log file exists
      copy:
        content: ""
        dest: /var/log/mail.log
        force: false
        group: postfix
        owner: postfix
        mode: "0600"

  tasks:
    - name: Run test
      block:
        - name: Run the role
          include_role:
            name: fedora.linux_system_roles.metrics
            public: true

        - name: Signal pmcd to ensure above path used by pmdapostfix
          command: pmstore pmcd.control.sighup 1
          changed_when: false
          when: __metrics_is_booted | bool

        - name: Check Postfix functionality
          include_tasks: "{{ item }}"
          loop:
            - check_postfix.yml
            - check_firewall_selinux.yml

        - name: Flush handlers
          meta: flush_handlers

      rescue:
        - name: Handle failure case
          include_tasks: handle_test_failure.yml

      always:
        - name: Restore state of services
          import_tasks: restore_services_state.yml
