---
- name: Manually gated apt safe upgrade
  hosts: all
  gather_facts: true
  become: true
  vars:
    allow_critical_manual: false
    allow_reboot: false
  pre_tasks:
    - name: Require target_update_class variable
      ansible.builtin.assert:
        that:
          - target_update_class is defined
          - target_update_class | length > 0
        fail_msg: "Pass -e target_update_class=<class>. Never run broad ungated upgrades."

    - name: Require target class to match host update_class
      ansible.builtin.assert:
        that:
          - update_class == target_update_class
        fail_msg: "Host update_class={{ update_class | default('unset') }} does not match target_update_class={{ target_update_class }}."

    - name: Block critical/manual hosts unless explicitly allowed
      ansible.builtin.assert:
        that:
          - update_class != 'critical_manual' or (allow_critical_manual | bool)
        fail_msg: "critical_manual hosts require -e allow_critical_manual=true and explicit maintenance planning."

  tasks:
    - name: Update apt package cache
      ansible.builtin.apt:
        update_cache: true
        cache_valid_time: 3600

    - name: Perform safe package upgrade only
      ansible.builtin.apt:
        upgrade: safe
      register: apt_upgrade_result

    - name: Check reboot-required marker
      ansible.builtin.stat:
        path: /var/run/reboot-required
      register: reboot_required

    - name: Refuse automatic reboot in MVP unless allowed
      ansible.builtin.debug:
        msg: "Reboot required but not performed; pass allow_reboot=true only in an approved maintenance window."
      when:
        - reboot_required.stat.exists
        - not (allow_reboot | bool)

    - name: Reboot only if explicitly allowed
      ansible.builtin.reboot:
        msg: "Nimrod managed update reboot"
        reboot_timeout: 600
      when:
        - reboot_required.stat.exists
        - allow_reboot | bool

    - name: Update summary for change log
      ansible.builtin.debug:
        msg:
          host: "{{ inventory_hostname }}"
          update_class: "{{ update_class }}"
          changed: "{{ apt_upgrade_result.changed }}"
          reboot_required: "{{ reboot_required.stat.exists }}"
          reboot_performed: "{{ reboot_required.stat.exists and (allow_reboot | bool) }}"
          runbook: "{{ runbook | default('unset') }}"
