---
- name: Universal Linux System Maintenance
  hosts: linux
  remote_user: root
  # Gather facts once at the start to determine OS family
  gather_facts: yes

  tasks:
    # --- DEBIAN / UBUNTU / PROXMOX ---
    - name: Debian-based Maintenance
      when: ansible_os_family == "Debian"
      block:
        - name: Update apt cache and upgrade all packages
          apt:
            upgrade: dist
            update_cache: yes
            cache_valid_time: 3600

        - name: Install baseline toolset (Debian)
          apt:
            name:
              - htop
              - make
              - git
              - curl
              - samba
              - fail2ban
              - sshpass
              - sudo
            state: present

        - name: Remove obsolete packages and kernels
          apt:
            autoremove: yes
            autoclean: yes

    # --- RHEL / ALMALINUX / ROCKY ---
    - name: RedHat-based Maintenance
      when: ansible_os_family == "RedHat"
      block:
        - name: Upgrade all packages (DNF)
          dnf:
            name: "*"
            state: latest
            update_cache: yes

        - name: Install baseline toolset (RHEL)
          dnf:
            name: [htop, make, nano, git, curl, fail2ban, samba, sshpass]
            state: present

        - name: Clean DNF metadata and cache
          command: dnf clean all
          changed_when: false

    # --- FINAL CHECK ---
    - name: Check if reboot is required
      stat:
        path: /var/run/reboot-required
      register: reboot_required_file

    - name: Notify if reboot is needed
      debug:
        msg: "Host {{ inventory_hostname }} requires a reboot to apply updates."
      when: reboot_required_file.stat.exists