# SPDX-License-Identifier: MIT
---
- name: Ensure that the cron is set up
  hosts: all
  tasks:
    - name: Determine if system is ostree and set flag
      when: not __aide_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:
            __aide_is_ostree: "{{ __ostree_booted_stat.stat.exists }}"

    - name: Install crontabs
      package:
        name: crontabs
        state: present
        use: "{{ (__aide_is_ostree | d(false)) | ternary('ansible.posix.rhel_rpm_ostree', omit) }}"

    - name: Create tempfile for crontab backup
      tempfile:
        prefix: aide_
        suffix: _crontab
      register: __aide_crontab_backup

    - name: Backup crontab
      copy:
        src: /etc/crontab
        dest: "{{ __aide_crontab_backup.path }}"
        remote_src: true
        mode: preserve

    - name: Run tests
      block:
        - name: Run the role and set up cron
          ansible.builtin.include_role:
            name: fedora.linux_system_roles.aide
          vars:
            aide_init: true
            aide_cron_check: true
            aide_cron_interval: "0 12 * * *"

        - name: Check file content
          ansible.builtin.lineinfile:
            path: /etc/crontab
            regexp: "^.* root /usr/sbin/aide --check"
            line: "0 12 * * * root /usr/sbin/aide --check"
            state: present
          register: result
          failed_when: result is changed

        - name: Run the role and and do not touch cron
          ansible.builtin.include_role:
            name: fedora.linux_system_roles.aide
          vars:
            aide_cron_interval: "0 1 * * *"

        - name: Ensure file is not changed
          ansible.builtin.lineinfile:
            path: /etc/crontab
            regexp: "^.* root /usr/sbin/aide --check"
            line: "0 12 * * * root /usr/sbin/aide --check"
            state: present
          register: result
          failed_when: result is changed

        - name: Run the role and disable cron
          ansible.builtin.include_role:
            name: fedora.linux_system_roles.aide
          vars:
            aide_cron_check: false

        - name: Ensure aide cron is removed
          ansible.builtin.lineinfile:
            path: /etc/crontab
            regexp: "^.* root /usr/sbin/aide --check"
            line: "0 12 * * * root /usr/sbin/aide --check"
            state: present
          register: result
          failed_when: not result is changed

      always:
        - name: Restore crontab
          copy:
            src: "{{ __aide_crontab_backup.path }}"
            dest: /etc/crontab
            remote_src: true
            mode: preserve

        - name: Delete tempfile
          file:
            path: "{{ __aide_crontab_backup.path }}"
            state: absent
