---

### tags:
###   update_connections

- name: "Checking connect is running on <{{ connect_base_url }}>"
  delegate_to: 127.0.0.1
  become: false
  uri:
    url: "{{ http_s }}://{{ connect_base_url }}/api/profile-info"
    method: GET
    headers:
      "Smardigo-User-Token": "{{ smardigo_auth_token_value }}"
    status_code: [200]
  register: connect_profile_info
  delay: 15
  retries: 10
  until: connect_profile_info.status in [200]
  tags:
    - update_connections

- name: "Reading connections from <{{ connect_base_url }}>"
  delegate_to: 127.0.0.1
  become: false
  uri:
    url: "{{ http_s }}://{{ connect_base_url }}/api/datasource-connections"
    method: GET
    headers:
      "Smardigo-User-Token": "{{ smardigo_auth_token_value }}"
    status_code: [200,201]
  register: connect_connections_result
  tags:
    - update_connections

- name: "Reading connection ids from <{{ connect_base_url }}>"
  set_fact:  
    connect_connection_ids: "{{ connect_connections_result.json | community.general.json_query(querystr) | list | flatten }}"
  vars:
    querystr: "[[*].id]"
  tags:
    - update_connections

- name: "Printing connection ids for <{{ connect_base_url }}>"
  debug:
    msg: "{{ connect_connection_ids }}"
  when:
   - debug
  tags:
    - update_connections

- name: "Creating/Updating connections on <{{ connect_base_url }}>"
  delegate_to: 127.0.0.1
  become: false
  uri:
    url: "{{ http_s }}://{{ connect_base_url }}/api/datasource-connections"
    method: "{% if item.id in connect_connection_ids %}PUT{% else %}POST{% endif %}"
    body_format: json
    body: '{{ item | to_json }}'
    headers:
      "Smardigo-User-Token": "{{ smardigo_auth_token_value }}"
    status_code: [200,201]
  loop: "{{ connect_connections | default([]) }}"
  loop_control:
    label: "{{ item.id }}" # do not print confidential data
  changed_when: true
  tags:
    - update_connections
