---
- name: Check if Swarm is initialized
  ansible.builtin.shell: !unsafe "docker info --format '{{.Swarm.LocalNodeState}}'"
  register: swarm_status
  changed_when: false

# 1. İlk Manager'ın (Leader) başlatılması
- name: Initialize Docker Swarm (Leader)
  ansible.builtin.shell: >
    docker swarm init
    --advertise-addr {{ private_ip }}
  when: 
    - inventory_hostname == groups['app'][0]
    - swarm_status.stdout != 'active'
  register: swarm_init_result

# 2. Join Token'ların alınması (Sadece Leader üzerinden)
- name: Get Swarm Manager Join Token
  ansible.builtin.shell: docker swarm join-token manager -q
  register: manager_token
  delegate_to: "{{ groups['app'][0] }}"
  when: inventory_hostname == groups['app'][0]
  changed_when: false

- name: Get Swarm Worker Join Token
  ansible.builtin.shell: docker swarm join-token worker -q
  register: worker_token
  delegate_to: "{{ groups['app'][0] }}"
  when: inventory_hostname == groups['app'][0]
  changed_when: false

# 3. Diğer App sunucularının Manager olarak katılması (Prod HA için)
- name: Join Swarm as Manager
  ansible.builtin.shell: >
    docker swarm join
    --token {{ hostvars[groups['app'][0]]['manager_token']['stdout'] }}
    --advertise-addr {{ private_ip }}
    {{ swarm_manager_ip }}:2377
  when:
    - inventory_hostname in groups['app']
    - inventory_hostname != groups['app'][0]
    - swarm_status.stdout != 'active'

# 4. DB sunucularının Worker olarak katılması
- name: Join Swarm as Worker
  ansible.builtin.shell: >
    docker swarm join
    --token {{ hostvars[groups['app'][0]]['worker_token']['stdout'] }}
    --advertise-addr {{ private_ip }}
    {{ swarm_manager_ip }}:2377
  when:
    - inventory_hostname in groups['db']
    - swarm_status.stdout != 'active'

# 5. Node Etiketleri (Labels)
# iklimco-net overlay network is created and owned by the Swarm stack (docker-stack-infra_db-prod.yml).
# Stack-owned networks get full Docker DNS (service VIPs, aliases). No manual creation needed.
- name: Label App nodes (service)
  ansible.builtin.shell: docker node update --label-add type=service {{ inventory_hostname }}
  delegate_to: "{{ groups['app'][0] }}"
  when: inventory_hostname in groups['app']
  changed_when: false

- name: Label DB nodes (db)
  ansible.builtin.shell: docker node update --label-add role=db {{ inventory_hostname }}
  delegate_to: "{{ groups['app'][0] }}"
  when: inventory_hostname in groups['db']
  changed_when: false
