---
# Targeted Ansible update for confirmed Debian/Ubuntu hosts
# Excludes Synology, TrueNAS, Home Assistant, and unreachable hosts
# Created: February 8, 2026

- name: Update and upgrade Ansible on confirmed Linux hosts
  hosts: homelab,pi-5,vish-concord-nuc,pve
  gather_facts: yes
  become: yes
  serial: 1  # Process one host at a time for better control

  tasks:
    - name: Display target host information
      debug:
        msg: |
          Processing: {{ inventory_hostname }} ({{ ansible_host }})
          OS: {{ ansible_distribution }} {{ ansible_distribution_version }}
          Python: {{ ansible_python_version }}

    - name: Check if apt is available
      stat:
        path: /usr/bin/apt
      register: apt_available

    - name: Skip non-Debian hosts
      debug:
        msg: "Skipping {{ inventory_hostname }} - apt not available"
      when: not apt_available.stat.exists

    - name: Update apt package cache (with retry)
      apt:
        update_cache: yes
        cache_valid_time: 0  # Force update
      register: apt_update_result
      retries: 3
      delay: 10
      when: apt_available.stat.exists
      ignore_errors: yes

    - name: Display apt update status
      debug:
        msg: |
          APT update on {{ inventory_hostname }}:
          {% if apt_update_result is succeeded %}
          ✅ Success - Cache updated
          {% elif apt_update_result is failed %}
          ❌ Failed - {{ apt_update_result.msg | default('Unknown error') }}
          {% else %}
          ⏭️  Skipped - apt not available
          {% endif %}

    - name: Check if Ansible is installed
      command: which ansible
      register: ansible_installed
      changed_when: false
      failed_when: false
      when: apt_available.stat.exists and apt_update_result is succeeded

    - name: Get current Ansible version if installed
      command: ansible --version
      register: current_ansible_version
      changed_when: false
      failed_when: false
      when: ansible_installed is succeeded and ansible_installed.rc == 0

    - name: Display current Ansible status
      debug:
        msg: |
          Ansible status on {{ inventory_hostname }}:
          {% if ansible_installed is defined and ansible_installed.rc == 0 %}
          📦 Installed: {{ current_ansible_version.stdout_lines[0] if current_ansible_version.stdout_lines else 'Version check failed' }}
          {% else %}
          📦 Not installed
          {% endif %}

    - name: Install or upgrade Ansible
      apt:
        name: ansible
        state: latest
        update_cache: no  # We already updated above
      register: ansible_upgrade_result
      when: apt_available.stat.exists and apt_update_result is succeeded
      ignore_errors: yes

    - name: Display Ansible installation/upgrade results
      debug:
        msg: |
          Ansible operation on {{ inventory_hostname }}:
          {% if ansible_upgrade_result is succeeded %}
            {% if ansible_upgrade_result.changed %}
          ✅ {{ 'Installed' if ansible_installed.rc != 0 else 'Upgraded' }} successfully
            {% else %}
          ℹ️  Already at latest version
            {% endif %}
          {% elif ansible_upgrade_result is failed %}
          ❌ Failed: {{ ansible_upgrade_result.msg | default('Unknown error') }}
          {% else %}
          ⏭️  Skipped due to previous errors
          {% endif %}

    - name: Verify final Ansible version
      command: ansible --version
      register: final_ansible_version
      changed_when: false
      failed_when: false
      when: ansible_upgrade_result is succeeded

    - name: Final status summary
      debug:
        msg: |
          === SUMMARY FOR {{ inventory_hostname | upper }} ===
          Host: {{ ansible_host }}
          OS: {{ ansible_distribution }} {{ ansible_distribution_version }}
          APT Update: {{ '✅ Success' if apt_update_result is succeeded else '❌ Failed' if apt_update_result is defined else '⏭️ Skipped' }}
          Ansible: {% if final_ansible_version is succeeded %}{{ final_ansible_version.stdout_lines[0] }}{% elif ansible_upgrade_result is succeeded %}{{ 'Installed/Updated' if ansible_upgrade_result.changed else 'Already current' }}{% else %}{{ '❌ Failed or skipped' }}{% endif %}

  post_tasks:
    - name: Clean up apt cache
      apt:
        autoclean: yes
      when: apt_available.stat.exists and apt_update_result is succeeded
      ignore_errors: yes
