---
- name: Check APT Proxy Configuration on Debian/Ubuntu hosts
  hosts: debian_clients
  become: no
  gather_facts: yes

  vars:
    expected_proxy_host: 100.103.48.78  # calypso
    expected_proxy_port: 3142
    apt_proxy_file: /etc/apt/apt.conf.d/01proxy
    expected_proxy_url: "http://{{ expected_proxy_host }}:{{ expected_proxy_port }}/"

  tasks:
    # ---------- System Detection ----------
    - name: Detect OS family
      ansible.builtin.debug:
        msg: "Host {{ inventory_hostname }} is running {{ ansible_os_family }} {{ ansible_distribution }} {{ ansible_distribution_version }}"

    - name: Skip non-Debian systems
      ansible.builtin.meta: end_host
      when: ansible_os_family != "Debian"

    # ---------- APT Proxy Configuration Check ----------
    - name: Check if APT proxy config file exists
      ansible.builtin.stat:
        path: "{{ apt_proxy_file }}"
      register: proxy_file_stat

    - name: Read APT proxy configuration (if exists)
      ansible.builtin.slurp:
        src: "{{ apt_proxy_file }}"
      register: proxy_config_content
      when: proxy_file_stat.stat.exists
      failed_when: false

    - name: Parse proxy configuration
      ansible.builtin.set_fact:
        proxy_config_decoded: "{{ proxy_config_content.content | b64decode }}"
      when: proxy_file_stat.stat.exists and proxy_config_content is defined

    # ---------- Network Connectivity Test ----------
    - name: Test connectivity to expected proxy server
      ansible.builtin.uri:
        url: "http://{{ expected_proxy_host }}:{{ expected_proxy_port }}/"
        method: HEAD
        timeout: 10
      register: proxy_connectivity
      failed_when: false
      changed_when: false

    # ---------- APT Configuration Analysis ----------
    - name: Check current APT proxy settings via apt-config
      ansible.builtin.command: apt-config dump Acquire::http::Proxy
      register: apt_config_proxy
      changed_when: false
      failed_when: false
      become: yes

    - name: Test APT update with current configuration (dry-run)
      ansible.builtin.command: apt-get update --print-uris --dry-run
      register: apt_update_test
      changed_when: false
      failed_when: false
      become: yes

    # ---------- Analysis and Reporting ----------
    - name: Analyze proxy configuration status
      ansible.builtin.set_fact:
        proxy_status:
          file_exists: "{{ proxy_file_stat.stat.exists }}"
          file_content: "{{ proxy_config_decoded | default('N/A') }}"
          expected_config: "Acquire::http::Proxy \"{{ expected_proxy_url }}\";"
          proxy_reachable: "{{ proxy_connectivity.status is defined and (proxy_connectivity.status == 200 or proxy_connectivity.status == 406) }}"
          apt_config_output: "{{ apt_config_proxy.stdout | default('N/A') }}"
          using_expected_proxy: "{{ (proxy_config_decoded | default('')) is search(expected_proxy_host) }}"

    # ---------- Health Assertions ----------
    - name: Assert APT proxy is properly configured
      ansible.builtin.assert:
        that:
          - proxy_status.file_exists
          - proxy_status.using_expected_proxy
          - proxy_status.proxy_reachable
        success_msg: "✅ {{ inventory_hostname }} is correctly using APT proxy {{ expected_proxy_host }}:{{ expected_proxy_port }}"
        fail_msg: "❌ {{ inventory_hostname }} APT proxy configuration issues detected"
      failed_when: false
      register: proxy_assertion

    # ---------- Detailed Summary ----------
    - name: Display comprehensive proxy status
      ansible.builtin.debug:
        msg: |

          🔍 APT Proxy Status for {{ inventory_hostname }}:
          ================================================
          OS: {{ ansible_distribution }} {{ ansible_distribution_version }}

          📁 Configuration File:
            Path: {{ apt_proxy_file }}
            Exists: {{ proxy_status.file_exists }}
            Content: {{ proxy_status.file_content | regex_replace('\n', ' ') }}

          🎯 Expected Configuration:
            {{ proxy_status.expected_config }}

          🌐 Network Connectivity:
            Proxy Server: {{ expected_proxy_host }}:{{ expected_proxy_port }}
            Reachable: {{ proxy_status.proxy_reachable }}
            Response: {{ proxy_connectivity.status | default('N/A') }}

          ⚙️  Current APT Config:
            {{ proxy_status.apt_config_output }}

          ✅ Status: {{ 'CONFIGURED' if proxy_status.using_expected_proxy else 'NOT CONFIGURED' }}
          🔗 Connectivity: {{ 'OK' if proxy_status.proxy_reachable else 'FAILED' }}

          {% if not proxy_assertion.failed %}
          🎉 Result: APT proxy is working correctly!
          {% else %}
          ⚠️  Result: APT proxy needs attention
          {% endif %}

    # ---------- Recommendations ----------
    - name: Provide configuration recommendations
      ansible.builtin.debug:
        msg: |

          💡 Recommendations for {{ inventory_hostname }}:
          {% if not proxy_status.file_exists %}
          - Create APT proxy config: echo 'Acquire::http::Proxy "{{ expected_proxy_url }}";' | sudo tee {{ apt_proxy_file }}
          {% endif %}
          {% if not proxy_status.proxy_reachable %}
          - Check network connectivity to {{ expected_proxy_host }}:{{ expected_proxy_port }}
          - Verify calypso apt-cacher-ng service is running
          {% endif %}
          {% if proxy_status.file_exists and not proxy_status.using_expected_proxy %}
          - Update proxy configuration to use {{ expected_proxy_url }}
          {% endif %}
      when: proxy_assertion.failed

    # ---------- Summary Statistics ----------
    - name: Record results for summary
      ansible.builtin.set_fact:
        host_proxy_result:
          hostname: "{{ inventory_hostname }}"
          configured: "{{ proxy_status.using_expected_proxy }}"
          reachable: "{{ proxy_status.proxy_reachable }}"
          status: "{{ 'OK' if (proxy_status.using_expected_proxy and proxy_status.proxy_reachable) else 'NEEDS_ATTENTION' }}"

# ---------- Final Summary Report ----------
- name: APT Proxy Summary Report
  hosts: localhost
  gather_facts: no
  run_once: true

  vars:
    expected_proxy_host: 100.103.48.78  # calypso
    expected_proxy_port: 3142

  tasks:
    - name: Collect all host results
      ansible.builtin.set_fact:
        all_results: "{{ groups['debian_clients'] | map('extract', hostvars) | selectattr('host_proxy_result', 'defined') | map(attribute='host_proxy_result') | list }}"
      when: groups['debian_clients'] is defined

    - name: Generate summary statistics
      ansible.builtin.set_fact:
        summary_stats:
          total_hosts: "{{ all_results | length }}"
          configured_hosts: "{{ all_results | selectattr('configured', 'equalto', true) | list | length }}"
          reachable_hosts: "{{ all_results | selectattr('reachable', 'equalto', true) | list | length }}"
          healthy_hosts: "{{ all_results | selectattr('status', 'equalto', 'OK') | list | length }}"
      when: all_results is defined

    - name: Display final summary
      ansible.builtin.debug:
        msg: |

          📊 APT PROXY HEALTH SUMMARY
          ===========================
          Total Debian Clients: {{ summary_stats.total_hosts | default(0) }}
          Properly Configured: {{ summary_stats.configured_hosts | default(0) }}
          Proxy Reachable: {{ summary_stats.reachable_hosts | default(0) }}
          Fully Healthy: {{ summary_stats.healthy_hosts | default(0) }}

          🎯 Target Proxy: calypso ({{ expected_proxy_host }}:{{ expected_proxy_port }})

          {% if summary_stats.healthy_hosts | default(0) == summary_stats.total_hosts | default(0) %}
          🎉 ALL SYSTEMS OPTIMAL - APT proxy working perfectly across all clients!
          {% else %}
          ⚠️  Some systems need attention - check individual host reports above
          {% endif %}
      when: summary_stats is defined
