---
# file: roles/crontab/tasks/main.yml

- name: "Install cron package"
  apt:
    name: cron
  tags: crontab

- name: "Configuring cron tasks"
  ansible.builtin.cron:
    cron_file: "{{ item.cron_file | default(omit) }}"
    day: "{{ item.day | default(omit) }}"
    env: "{{ item.env | default(omit) }}"
    hour: "{{ item.hour | default(omit) }}"
    job: "{{ item.job | default(omit) }}"
    minute: "{{ item.minute | default(omit) }}"
    month: "{{ item.month | default(omit) }}"
    name: "{{ item.name }}"
    special_time: "{{ item.special_time | default(omit) }}"
    state: "{{ item.state | default(omit) }}"
    user: "{{ item.user | default(omit) }}"
    value: "{{ item.value | default(omit) }}"
    weekday: "{{ item.weekday | default(omit) }}"
    disabled: "{{ item.disabled | default(omit) }}"
  loop: "{{ cron_tasks }}"
  when: cron_tasks is defined
  tags: crontab

- name: "Silence selected root cron.d files via MAILTO"
  block:
    - name: "Check if cron files exist"
      ansible.builtin.stat:
        path: "/etc/cron.d/{{ item }}"
      loop: "{{ crontab_silence_files }}"
      register: crontab_file_stats
    - name: "Keep only existing cron files"
      ansible.builtin.set_fact:
        crontab_silence_files_existing: >-
          {{
            crontab_file_stats.results
            | selectattr('stat.exists', 'defined')
            | selectattr('stat.exists')
            | map(attribute='item')
            | list
          }}
    - name: "Silence existing root cron.d files"
      ansible.builtin.cron:
        name: MAILTO
        env: true
        value: ""
        cron_file: "{{ item }}"
        user: root
      loop: "{{ crontab_silence_files_existing }}"
  when: crontab_silence_files is defined and (crontab_silence_files | length) > 0
  tags: crontab
