---
- name: Install and configure nginx with stream module
  hosts: hip
  become: yes
  gather_facts: yes

  tasks:
    - name: Update apt cache
      apt:
        update_cache: yes
        cache_valid_time: 3600
      when: ansible_os_family == "Debian"

    - name: Install nginx with stream module
      apt:
        name: 
          - nginx
          - libnginx-mod-stream
        state: present
      when: ansible_os_family == "Debian"

    - name: Create stream log directory
      file:
        path: /var/log/nginx/stream
        state: directory
        owner: www-data
        group: adm
        mode: '0755'

    - name: Create stream config directory
      file:
        path: /etc/nginx/stream-conf.d
        state: directory
        owner: root
        group: root
        mode: '0755'

    - name: Deploy stream configuration
      template:
        src: templates/nginx/nginx-stream.conf.j2
        dest: /etc/nginx/stream-conf.d/default.conf
        owner: root
        group: root
        mode: '0644'
      notify: restart nginx

    - name: Configure main stream block in nginx.conf
      blockinfile:
        path: /etc/nginx/nginx.conf
        insertafter: EOF
        block: |
          stream {
              include /etc/nginx/stream-conf.d/*.conf;
          }
        marker: "### {mark} ANSIBLE MANAGED STREAM BLOCK ###"
      notify: restart nginx

    - name: Enable nginx service
      systemd:
        name: nginx
        enabled: yes
        state: started

  handlers:
    - name: restart nginx
      systemd:
        name: nginx
        state: restarted
        daemon_reload: yes
