---
- name: Calico | Set label for groups nodes
  command: "{{ bin_dir }}/calicoctl.sh label node  {{ inventory_hostname }} calico-group-id={{ calico_group_id }} --overwrite"
  changed_when: false
  register: calico_group_id_label
  until: calico_group_id_label is succeeded
  delay: "{{ retry_stagger | random + 3 }}"
  retries: 10
  when:
    - calico_group_id is defined

- name: Calico | Configure peering with route reflectors at global scope
  command:
    cmd: "{{ bin_dir }}/calicoctl.sh apply -f -"
    # revert when it's already a string
    stdin: "{{ stdin is string | ternary(stdin, stdin | to_json) }}"
  vars:
    stdin: >
      {"apiVersion": "projectcalico.org/v3",
      "kind": "BGPPeer",
      "metadata": {
        "name": "{{ calico_rr_id }}-to-node"
      },
      "spec": {
        "peerSelector": "calico-rr-id == '{{ calico_rr_id }}'",
        "nodeSelector": "calico-group-id == '{{ calico_group_id }}'"
      }}
  register: output
  retries: 4
  until: output.rc == 0
  delay: "{{ retry_stagger | random + 3 }}"
  when:
    - calico_rr_id is defined
    - calico_group_id is defined
    - ('calico_rr' in group_names)

- name: Calico | Configure peering with route reflectors at global scope
  command:
    cmd: "{{ bin_dir }}/calicoctl.sh apply -f -"
    # revert when it's already a string
    stdin: "{{ stdin is string | ternary(stdin, stdin | to_json) }}"
  vars:
    stdin: >
      {"apiVersion": "projectcalico.org/v3",
      "kind": "BGPPeer",
      "metadata": {
        "name": "peer-to-rrs"
      },
      "spec": {
        "nodeSelector": "!has(i-am-a-route-reflector)",
        "peerSelector": "has(i-am-a-route-reflector)"
      }}
  register: output
  retries: 4
  until: output.rc == 0
  delay: "{{ retry_stagger | random + 3 }}"
  with_items:
    - "{{ groups['calico_rr'] | default([]) }}"
  when:
    - inventory_hostname == groups['kube_control_plane'][0]
    - calico_rr_id is not defined or calico_group_id is not defined

- name: Calico | Configure route reflectors to peer with each other
  command:
    cmd: "{{ bin_dir }}/calicoctl.sh apply -f -"
    # revert when it's already a string
    stdin: "{{ stdin is string | ternary(stdin, stdin | to_json) }}"
  vars:
    stdin: >
      {"apiVersion": "projectcalico.org/v3",
      "kind": "BGPPeer",
      "metadata": {
        "name": "rr-mesh"
      },
      "spec": {
        "nodeSelector": "has(i-am-a-route-reflector)",
        "peerSelector": "has(i-am-a-route-reflector)"
      }}
  register: output
  retries: 4
  until: output.rc == 0
  delay: "{{ retry_stagger | random + 3 }}"
  with_items:
    - "{{ groups['calico_rr'] | default([]) }}"
  when:
    - inventory_hostname == groups['kube_control_plane'][0]
