---
- name: Configure Consul Auto-Discovery
  hosts: all
  become: yes
  vars:
    consul_servers:
      - "warden.tailnet-68f9.ts.net:8301"
      - "ch4.tailnet-68f9.ts.net:8301"
      - "ash3c.tailnet-68f9.ts.net:8301"
  
  tasks:
    - name: Backup current nomad.hcl
      copy:
        src: /etc/nomad.d/nomad.hcl
        dest: /etc/nomad.d/nomad.hcl.backup.{{ ansible_date_time.epoch }}
        remote_src: yes
        backup: yes

    - name: Update Consul configuration for auto-discovery
      blockinfile:
        path: /etc/nomad.d/nomad.hcl
        marker: "# {mark} ANSIBLE MANAGED CONSUL CONFIG"
        block: |
          consul {
            retry_join = [
              "warden.tailnet-68f9.ts.net:8301",
              "ch4.tailnet-68f9.ts.net:8301", 
              "ash3c.tailnet-68f9.ts.net:8301"
            ]
            server_service_name = "nomad"
            client_service_name = "nomad-client"
          }
        insertbefore: '^consul \{'
        replace: '^consul \{.*?\}'

    - name: Restart Nomad service
      systemd:
        name: nomad
        state: restarted
        enabled: yes

    - name: Wait for Nomad to be ready
      wait_for:
        port: 4646
        host: "{{ ansible_default_ipv4.address }}"
        delay: 5
        timeout: 30

    - name: Verify Consul connection
      shell: |
        NOMAD_ADDR=http://localhost:4646 nomad node status | grep -q "ready"
      register: nomad_ready
      failed_when: nomad_ready.rc != 0
      retries: 3
      delay: 10
