---

#
# This role adds dnf automatic package and configuration.
# We want this on any public facing Fedora installs so we
# can pick up security updates.
#
- name: Install and configure dnf-automatic
  when: ansible_pkg_mgr == 'dnf'

  vars:
    dnf: "{{ 5 if (ansible_distribution_major_version | int >= 41 and ansible_distribution == 'Fedora') else 4 }}"
    package: "{{ 'dnf5-plugin-automatic' if dnf == '5' else 'dnf-automatic' }}"
    timer: "{{ 'dnf5-automatic.timer' if dnf == '5' else 'dnf-automatic-install.timer' }}"
    confdir: "/etc/systemd/system/{{ timer }}.d"

  block:
    - name: Install dnf-automatic
      ansible.builtin.dnf:
        name: "{{ package }}"
        state: present
        disablerepo: updates
      tags:
      - packages

    - name: Install /etc/dnf/automatic.conf
      ansible.builtin.template:
        src: automatic.conf.j2
        dest: /etc/dnf/automatic.conf
        mode: '644'
      tags:
      - config

    - name: Create directory for drop-in units
      ansible.builtin.file:
        path: "{{ confdir }}"
        state: directory
        mode: "755"

    - name: Set dnf-automatic to execute only on Mon-Fri
      community.general.ini_file:
        path: "{{ confdir }}/weekdays.conf"
        section: Timer
        option: OnCalendar
        value: Mon..Fri *-*-* 6:00:00
        create: true
      notify: Restart dnf-automatic timer
      tags:
      - config

    - name: Enable and start dnf-automatic timer
      ansible.builtin.service:
        name: "{{ timer }}"
        enabled: true
        state: started
      tags:
      - config

    - name: Disable silly makecache timer
      ansible.builtin.systemd:
        name: dnf-makecache.timer
        masked: true
      ignore_errors: true
