---
- name: Set the environment for pflogsumm and install the package
  block:
  - name: Set the postfix logfile path in EL distributions
    set_fact:
      postfix_logfile: /var/log/maillog
    when: ansible_distribution_file_variety == "RedHat"

  - name: Install the postfix-perl-scripts package on EL
    ansible.builtin.yum:
      pkg: postfix-perl-scripts
      state: present
    when: ansible_distribution_file_variety == "RedHat"

  - name: Set the postfix logfile path in deb distributions
    set_fact:
      postfix_logfile: /var/log/mail.log
    when: ansible_distribution_file_variety == "Debian"

  - name: Install the pflogsumm package on deb
    ansible.builtin.apt:
      pkg: pflogsumm
      state: present
      cache_valid_time: 1800
    when: ansible_distribution_file_variety == "Debian"


  when: postfix_pflogsumm_reports
  tags: [ 'postfix', 'postfix_pflogsumm' ]

- name: Configure pflogsumm
  block:
  - name: Install the pflogsumm script
    ansible.builtin.template:
      src: pflogsumm_report.sh.j2
      dest: /usr/local/sbin/pflogsumm_report
      owner: root
      group: root
      mode: 0750

  - name: Install the pflogsumm cron job
    ansible.builtin.cron:
      name: pflogsumm report
      user: root
      job: /usr/local/sbin/pflogsumm_report
      special_time: daily
      cron_file: pflogsumm_report
      state: present

  - name: Create the pflogsumm report directory
    ansible.builtin.file:
      dest: '{{ postfix_pflogsumm_dir }}'
      state: directory
      owner: root
      group: root
      mode: 0750
    when: not postfix_pflogsumm_mail_report

  - name: Install the logrotate configuration for pflogsumm
    ansible.builtin.template:
      src: pflogsumm_logrotate.j2
      dest: /etc/logrotate.d/pflogsumm
      owner: root
      group: root
      mode: 0644
    when: not postfix_pflogsumm_mail_report

  when: postfix_pflogsumm_reports
  tags: [ 'postfix', 'postfix_pflogsumm' ]

- name: Remove the pflogsum configuration
  block:
  - name: Remove the pflogsum cron job
    ansible.builtin.cron:
      name: pflogsumm report
      user: root
      job: /usr/local/sbin/pflogsumm_report
      special_time: daily
      cron_file: pflogsumm_report
      state: present

  - name: Remove the pflogsumm logs directory
    ansible.builtin.file:
      dest: '{{ postfix_pflogsumm_dir }}'
      state: absent
  
  - name: Remove the logrotate entry for pglogsumm
    ansible.builtin.file:
      dest: /etc/logrotate.d/pflogsumm
      state: absent

  when: not postfix_pflogsumm_reports
  tags: [ 'postfix', 'postfix_pflogsumm' ]