---
- name: Install and configure Consul clients on all nodes
  hosts: all
  become: yes
  vars:
    consul_servers:
      - "100.117.106.136"  # ch4 (韩国)
      - "100.122.197.112"  # warden (北京)
      - "100.116.80.94"    # ash3c (美国)
  
  tasks:
    - name: Get Tailscale IP address
      shell: ip addr show tailscale0 | grep 'inet ' | awk '{print $2}' | cut -d/ -f1
      register: tailscale_ip_result
      changed_when: false

    - name: Set Tailscale IP fact
      set_fact:
        tailscale_ip: "{{ tailscale_ip_result.stdout }}"

    - name: Install Consul
      apt:
        name: consul
        state: present
        update_cache: yes

    - name: Create Consul data directory
      file:
        path: /opt/consul/data
        state: directory
        owner: consul
        group: consul
        mode: '0755'

    - name: Create Consul log directory
      file:
        path: /var/log/consul
        state: directory
        owner: consul
        group: consul
        mode: '0755'

    - name: Create Consul config directory
      file:
        path: /etc/consul.d
        state: directory
        owner: consul
        group: consul
        mode: '0755'

    - name: Generate Consul client configuration
      template:
        src: consul-client.hcl.j2
        dest: /etc/consul.d/consul.hcl
        owner: consul
        group: consul
        mode: '0644'
      notify: restart consul

    - name: Enable and start Consul service
      systemd:
        name: consul
        enabled: yes
        state: started
        daemon_reload: yes

  handlers:
    - name: restart consul
      systemd:
        name: consul
        state: restarted
