---

# Check the cluster is healthy
- include: check_cluster_health.yml

# Check if the member has v3 data already
# Run the migration only if the data are v2
- name: Check if there are any v3 data
  command: >
    etcdctl --cert {{ etcd_peer_cert_file }} --key {{ etcd_peer_key_file }} --cacert {{ etcd_peer_ca_file }} --endpoints 'https://{{ etcd_peer }}:{{ etcd_client_port }}' get "" --from-key --keys-only -w json --limit 1
  environment:
    ETCDCTL_API: 3
  register: l_etcdctl_output

- fail:
    msg: "Unable to get a number of v3 keys"
  when: l_etcdctl_output.rc != 0

- fail:
    msg: "The etcd has at least one v3 key"
  when: "'count' in (l_etcdctl_output.stdout | from_json) and (l_etcdctl_output.stdout | from_json).count != 0"


# TODO(jchaloup): once the until loop can be used over include/block,
#                 remove the repetive code
# - until loop not supported over include statement (nor block)
#   https://github.com/ansible/ansible/issues/17098
# - with_items not supported over block

# Check the cluster status for the first time
- include: check_cluster_status.yml

# Check the cluster status for the second time
- block:
  - debug:
      msg: "l_etcd_cluster_status_ok: {{ l_etcd_cluster_status_ok }}"
  - name: Wait a while before another check
    pause:
      seconds: 5
    when: not l_etcd_cluster_status_ok | bool

  - include: check_cluster_status.yml
    when: not l_etcd_cluster_status_ok | bool


# Check the cluster status for the third time
- block:
  - debug:
      msg: "l_etcd_cluster_status_ok: {{ l_etcd_cluster_status_ok }}"
  - name: Wait a while before another check
    pause:
      seconds: 5
    when: not l_etcd_cluster_status_ok | bool

  - include: check_cluster_status.yml
    when: not l_etcd_cluster_status_ok | bool
