---
- name: Deploy HAProxy + initial TCP config
  hosts: haproxy
  become: yes

  vars:
    haproxy_cfg_path: /etc/haproxy/haproxy.cfg

  tasks:

    - name: Convert backend_ips string to list
      set_fact:
        backend_list: "{{ backend_ips.split(',') }}"

    - name: Install HAProxy
      apt:
        name: haproxy
        state: present
        update_cache: yes

    - name: Deploy initial haproxy.cfg
      copy:
        dest: "{{ haproxy_cfg_path }}"
        owner: root
        group: root
        mode: '0644'
        content: |
          global
              log /dev/log local0
              log /dev/log local1 notice
              maxconn 4096
              user haproxy
              group haproxy
              daemon

          defaults
              mode http
              log global
              option tcplog
              timeout connect 5s
              timeout client  50s
              timeout server  50s

          frontend https_in
              mode tcp
              bind {{ frontend_ip }}:{{ frontend_port }}
              default_backend https_backend

          backend https_backend
              mode tcp
              balance {{ balance_type }}
{% for ip in backend_list %}
              server backend{{ loop.index }} {{ ip }}:{{ backend_port }} check
{% endfor %}

    - name: Restart HAProxy
      systemd:
        name: haproxy
        enabled: yes
        state: restarted
