---
- name: Install and configure Squid proxy on Ubuntu 24
  hosts: squid_servers
  become: true
  vars:
    squid_port: 3128
    squid_localnet: 192.168.77.0/24   # Change to match your LAN

  tasks:

    - name: Update apt cache
      ansible.builtin.apt:
        update_cache: yes

    - name: Install squid package
      ansible.builtin.apt:
        name: squid
        state: present

    - name: Backup original squid.conf
      ansible.builtin.copy:
        src: /etc/squid/squid.conf
        dest: /etc/squid/squid.conf.bak
        remote_src: yes
        backup: yes
      when: not ansible_check_mode

    - name: Configure Squid for LAN access and HTTPS
      ansible.builtin.blockinfile:
        path: /etc/squid/squid.conf
        marker: "# {mark} ANSIBLE MANAGED BLOCK"
        block: |
          # Define ACL for local network
          acl localnet src {{ squid_localnet }}

          # Define safe ports
          acl SSL_ports port 443
          acl Safe_ports port 80
          acl Safe_ports port 443
          acl CONNECT method CONNECT

          # Deny invalid ports
          http_access deny !Safe_ports
          http_access deny CONNECT !SSL_ports

          # Allow localhost
          http_access allow localhost

          # Allow local network
          http_access allow localnet

          # Deny everything else
          http_access deny all

          # Listen port
          http_port {{ squid_port }}

          coredump_dir /var/spool/squid
      notify:
        - restart squid

    - name: Ensure Squid service is enabled and running
      ansible.builtin.service:
        name: squid
        state: started
        enabled: true

  handlers:
    - name: restart squid
      ansible.builtin.service:
        name: squid
        state: restarted
