---
- name: Configure APT Proxy on Debian/Ubuntu hosts
  hosts: debian_clients
  become: yes
  gather_facts: yes

  vars:
    apt_proxy_host: 100.103.48.78
    apt_proxy_port: 3142
    apt_proxy_file: /etc/apt/apt.conf.d/01proxy

  tasks:
    - name: Verify OS compatibility
      ansible.builtin.assert:
        that:
          - ansible_os_family == "Debian"
        fail_msg: "Host {{ inventory_hostname }} is not Debian-based. Skipping."
        success_msg: "Host {{ inventory_hostname }} is Debian-based."
      tags: verify

    - name: Create APT proxy configuration
      ansible.builtin.copy:
        dest: "{{ apt_proxy_file }}"
        owner: root
        group: root
        mode: '0644'
        content: |
          Acquire::http::Proxy "http://{{ apt_proxy_host }}:{{ apt_proxy_port }}/";
          Acquire::https::Proxy "false";
      register: proxy_conf
      tags: config

    - name: Ensure APT cache directories exist
      ansible.builtin.file:
        path: /var/cache/apt/archives
        state: directory
        owner: root
        group: root
        mode: '0755'
      tags: config

    - name: Test APT proxy connection (dry-run)
      ansible.builtin.command: >
        apt-get update --print-uris -o Acquire::http::Proxy="http://{{ apt_proxy_host }}:{{ apt_proxy_port }}/"
      register: apt_proxy_test
      changed_when: false
      failed_when: apt_proxy_test.rc != 0
      tags: verify

    - name: Display proxy test result
      ansible.builtin.debug:
        msg: |
          ✅ {{ inventory_hostname }} is using APT proxy {{ apt_proxy_host }}:{{ apt_proxy_port }}
          {{ apt_proxy_test.stdout | default('') }}
      when: apt_proxy_test.rc == 0
      tags: verify

    - name: Display failure if APT proxy test failed
      ansible.builtin.debug:
        msg: "⚠️  {{ inventory_hostname }} failed to reach APT proxy at {{ apt_proxy_host }}:{{ apt_proxy_port }}"
      when: apt_proxy_test.rc != 0
      tags: verify
