---
- name: Zero-downtime rolling patch with HAProxy drain and health gate
  hosts: localhost
  connection: local
  gather_facts: false
  vars:
    health_path: /healthz
    receipt_dir: "{{ playbook_dir }}/.patch-receipts"
  tasks:
    - name: Validate explicit stage and authorization
      ansible.builtin.assert:
        that:
          - not ansible_check_mode
          - (patch_apply | default(false)) is sameas true
          - (patch_stage | default('')) in ['canary', 'peer']
          - (patch_ticket | default('')) is match('^LAB-[A-Za-z0-9_-]{1,32}$')
          - (patch_nevra | default('')) | length > 0
          - (patch_repo_id | default('')) | length > 0
        fail_msg: >-
          Pass -e '{"patch_stage":"canary|peer","patch_apply":true,"patch_ticket":"LAB-001",
          "patch_nevra":"pkg-0:ver-rel.arch","patch_repo_id":"lab-snapshot-YYYY-MM-DD"}'.

    - name: Select target host and receipt path
      ansible.builtin.set_fact:
        target_host: "{{ groups['web_' ~ patch_stage][0] }}"
        canary_host: "{{ groups['web_canary'][0] }}"
        receipt_file: "{{ receipt_dir }}/{{ patch_ticket }}.json"

    - name: Require per-host inventory opt-in
      ansible.builtin.assert:
        that:
          - (hostvars[target_host].patch_opt_in | default(false)) is sameas true
        fail_msg: "Set patch_opt_in: true on {{ target_host }} only before running."

    - name: Enforce peer promotion gate (separate approval + fresh canary receipt + live canary health)
      when: patch_stage == 'peer'
      block:
        - name: Require explicit human peer approval
          ansible.builtin.assert:
            that:
              - (patch_peer_approved | default(false)) is sameas true
            fail_msg: "Peer stage requires -e '{\"patch_peer_approved\":true}' after canary review."

        - name: Verify canary receipt exists
          ansible.builtin.stat:
            path: "{{ receipt_file }}"
          register: rcpt_stat

        - name: Assert receipt exists
          ansible.builtin.assert:
            that:
              - rcpt_stat.stat.exists
            fail_msg: "Missing canary receipt {{ receipt_file }}. Run canary stage first."

        - name: Recheck live canary HTTP health before touching peer
          ansible.builtin.uri:
            url: "http://{{ canary_host }}{{ health_path }}"
            status_code: 200
            return_content: true
            use_proxy: false
          register: canary_recheck

        - name: Assert canary body matches expected identity
          ansible.builtin.assert:
            that:
              - (canary_recheck.content | trim) == ("ok:" ~ canary_host)
            fail_msg: "Canary {{ canary_host }} failed live health check; holding peer!"

    - name: Drain target backend cleanly from all HAProxy nodes
      ansible.builtin.shell: |
        printf 'set server %s state drain\n' '{{ hostvars[target_host].haproxy_backend_name }}' | socat stdio /var/lib/haproxy/stats
      loop: "{{ groups['lb'] }}"
      delegate_to: "{{ item }}"
      become: true
      changed_when: true

    - name: Patch target host from approved local snapshot repository
      delegate_to: "{{ target_host }}"
      become: true
      block:
        - name: Verify root filesystem has at least 1024 MiB free
          ansible.builtin.shell: |
            avail=$(df -Pm / | awk 'NR==2 {print $4}')
            (( avail >= 1024 ))
          changed_when: false

        - name: Install exact approved package build from immutable snapshot repo
          ansible.builtin.dnf:
            name: "{{ patch_nevra }}"
            state: present
            allow_downgrade: false
            allowerasing: false
            disable_gpg_check: false
            install_weak_deps: false
            disablerepo: ['*']
            enablerepo: ["{{ patch_repo_id }}"]
          register: dnf_out

        - name: Check if a reboot is required (dnf needs-restarting -r)
          ansible.builtin.command:
            argv: [dnf, needs-restarting, -r]
          register: reboot_hint
          changed_when: false
          failed_when: reboot_hint.rc not in [0, 1]

        - name: Hold if reboot is required without approval
          ansible.builtin.assert:
            that:
              - reboot_hint.rc == 0 or (patch_reboot_approved | default(false))
            fail_msg: "Reboot required on {{ target_host }}; obtain approval and rerun with patch_reboot_approved=true."

        - name: Reboot target if required and approved
          ansible.builtin.reboot:
            reboot_timeout: 180
            test_command: systemctl is-active nginx
          when: reboot_hint.rc == 1 and (patch_reboot_approved | default(false))

    - name: Validate direct HTTP health on target before re-enabling in HAProxy
      ansible.builtin.uri:
        url: "http://{{ target_host }}{{ health_path }}"
        status_code: 200
        return_content: true
        use_proxy: false
      register: post_health

    - name: Assert target health body matches expected host
      ansible.builtin.assert:
        that:
          - (post_health.content | trim) == ("ok:" ~ target_host)
        fail_msg: "Post-patch health failed on {{ target_host }}; leaving backend drained in HAProxy!"

    - name: Re-enable target backend in all HAProxy nodes
      ansible.builtin.shell: |
        printf 'set server %s state ready\n' '{{ hostvars[target_host].haproxy_backend_name }}' | socat stdio /var/lib/haproxy/stats
      loop: "{{ groups['lb'] }}"
      delegate_to: "{{ item }}"
      become: true
      changed_when: true

    - name: Write canary receipt after successful canary validation
      when: patch_stage == 'canary'
      block:
        - name: Ensure receipt directory exists
          ansible.builtin.file:
            path: "{{ receipt_dir }}"
            state: directory
            mode: '0700'

        - name: Save canary receipt JSON
          ansible.builtin.copy:
            dest: "{{ receipt_file }}"
            mode: '0600'
            content: >-
              {{ {'ticket': patch_ticket, 'nevra': patch_nevra, 'repo': patch_repo_id,
                  'host': target_host, 'issued_at': lookup('ansible.builtin.pipe', 'date +%s') | int} | to_nice_json }}
