#  Copyright 2022 Dell Inc. or its subsidiaries. All Rights Reserved.
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
---

- name: Authentication failure alert mail
  hosts: localhost
  connection: local
  vars:
    alert_file_path: /tmp/alerting
    auth_failure_check_time: 60
    auth_failure_search_key: "authentication failure"
    auth_failure_info_file: "{{ alert_file_path }}/auth_failure_{{ ansible_date_time.iso8601_basic_short }}.txt"
    auth_failure_mail_subject: "Alert - Authentication Failure"
    auth_failure_mail_body: "Attached the authentication failure report"
    auth_failure_mail_sender: omnia-alert
    file_mode: 644
  tasks:
    - name: Check auth failure in last {{ auth_failure_check_time }} minutes
      shell: journalctl -u sshd --since "{{ auth_failure_check_time }} minutes ago" | grep "{{ auth_failure_search_key }}"
      changed_when: false
      failed_when: false
      register: auth_failure_check

    - name: Create alerting log directory
      file:
        path: "{{ alert_file_path }}"
        state: directory
        mode: "{{ file_mode }}"

    - name: Save the authentication failure info
      copy:
        dest: "{{ auth_failure_info_file }}"
        content: |
          "{{ auth_failure_check.stdout }}"
        mode: "{{ file_mode }}"
      when: auth_failure_search_key in auth_failure_check.stdout

    - name: Sent mail on auth failure
      community.general.mail:
        subject: "{{ auth_failure_mail_subject }}"
        body: "{{ auth_failure_mail_body }}"
        sender: "{{ auth_failure_mail_sender }}"
        to: "{{ alert_email_address }}"
        attach:
          - "{{ auth_failure_info_file }}"
      when: auth_failure_search_key in auth_failure_check.stdout

    - name: Delete the authentication failure info file
      file:
        path: "{{ auth_failure_info_file }}"
        state: absent