---
- name: Configurer HAProxy avec Let's Encrypt (version fixée)
  hosts: edge
  become: true
  gather_facts: true

  vars:
    domain: "{{ domain | default('veza.talas.fr') }}"
    acme_email: "{{ acme_email | default('ops@talas.fr') }}"
    haproxy_container: "veza-haproxy"

  tasks:
    - name: Installer les packages de base dans HAProxy
      command: |
        incus exec {{ haproxy_container }} -- apt update
        incus exec {{ haproxy_container }} -- apt install -y haproxy certbot nginx-light curl
      register: install_result
      failed_when: false

    - name: Créer les répertoires nécessaires
      command: |
        incus exec {{ haproxy_container }} -- mkdir -p /etc/haproxy/certs /var/www/acme

    - name: Créer la configuration HAProxy directement dans le conteneur
      command: |
        incus exec {{ haproxy_container }} -- bash -c 'cat > /etc/haproxy/haproxy.cfg << EOF
        global
            daemon
            maxconn 2000
            log stdout local0
            tune.ssl.default-dh-param 2048

        defaults
            mode http
            log global
            option httplog
            option dontlognull
            timeout connect 5000
            timeout client 50000
            timeout server 50000

        frontend http_front
            bind *:80
            acl letsencrypt path_beg /.well-known/acme-challenge/
            use_backend letsencrypt if letsencrypt
            redirect scheme https code 301 if !letsencrypt

        backend letsencrypt
            server certbot 127.0.0.1:8888

        frontend https_front
            bind *:443 ssl crt /etc/haproxy/certs/{{ domain }}.pem alpn h2,http/1.1
            http-response set-header Strict-Transport-Security "max-age=31536000; includeSubDomains"
            
            acl is_api path_beg /api
            acl is_ws path_beg /ws
            acl is_stream path_beg /stream
            
            use_backend be_api if is_api
            use_backend be_ws if is_ws
            use_backend be_stream if is_stream
            default_backend be_web

        backend be_api
            balance roundrobin
            server api1 10.20.0.101:8080 check

        backend be_ws
            balance roundrobin
            server ws1 10.20.0.102:8081 check

        backend be_stream
            balance roundrobin
            server stream1 10.20.0.103:8082 check

        backend be_web
            balance roundrobin
            server web1 10.20.0.104:3000 check
        EOF'

    - name: Créer certificat auto-signé temporaire
      command: |
        incus exec {{ haproxy_container }} -- openssl req -x509 -newkey rsa:2048 \
          -keyout /etc/haproxy/certs/{{ domain }}.pem \
          -out /etc/haproxy/certs/{{ domain }}.pem \
          -days 365 -nodes -subj "/CN={{ domain }}"

    - name: Démarrer HAProxy
      command: |
        incus exec {{ haproxy_container }} -- systemctl enable haproxy
        incus exec {{ haproxy_container }} -- systemctl restart haproxy

    - name: Configurer nginx pour ACME
      command: |
        incus exec {{ haproxy_container }} -- bash -c 'cat > /etc/nginx/sites-available/acme << EOF
        server {
            listen 127.0.0.1:8888;
            root /var/www/acme;
            location /.well-known/acme-challenge/ {
                try_files \$uri =404;
            }
        }
        EOF'

    - name: Activer le site nginx
      command: |
        incus exec {{ haproxy_container }} -- ln -sf /etc/nginx/sites-available/acme /etc/nginx/sites-enabled/
        incus exec {{ haproxy_container }} -- rm -f /etc/nginx/sites-enabled/default
        incus exec {{ haproxy_container }} -- systemctl restart nginx

    - name: Obtenir certificat Let's Encrypt
      command: |
        incus exec {{ haproxy_container }} -- certbot certonly \
          --webroot -w /var/www/acme \
          -d {{ domain }} \
          --email {{ acme_email }} \
          --agree-tos --non-interactive
      register: certbot_result
      failed_when: false

    - name: Créer le PEM pour HAProxy
      command: |
        incus exec {{ haproxy_container }} -- bash -c \
          'cat /etc/letsencrypt/live/{{ domain }}/fullchain.pem \
               /etc/letsencrypt/live/{{ domain }}/privkey.pem \
               > /etc/haproxy/certs/{{ domain }}.pem'
      when: certbot_result.rc == 0

    - name: Recharger HAProxy
      command: |
        incus exec {{ haproxy_container }} -- systemctl reload haproxy
