---

- name: "Authenticate on keycloak for {{ inventory_hostname }}"
  include_role:
    name: keycloak
    tasks_from: _authenticate

- name: "Creating smardigo user token"
  delegate_to: 127.0.0.1
  become: false
  smardigo_user_token:
    secret:  "{{ connect_jwt_secret }}"
    user_id: "{{ management_admin_username }}"
  register: smardigo_user_token_result

- name: "Setting smardigo_auth_token_value as fact"
  set_fact:
    smardigo_auth_token_value: "{{ smardigo_user_token_result.token }}"

- name: "Reading all pmci users from <{{ management_base_url }}>"
  delegate_to: 127.0.0.1
  become: false
  uri:
    url: "{{ http_s }}://{{ management_base_url }}/api/v1/scopes/{{ sma_management_scope_id }}/groups/workflow/members?roleIds={{ sma_management_role_id }}"
    method: GET
    headers:
      "Smardigo-User-Token": "{{ smardigo_auth_token_value }}"
    status_code: [200,201]
  register: pmci_users_results

- name: "Reading users from <{{ management_base_url }}>"
  delegate_to: 127.0.0.1
  become: false
  set_fact:
    pmci_users: "{{ pmci_users_results.json | json_query(querystr1) | json_query(querystr2) | unique | sort | default([]) }}"
  vars:
    querystr1: "[*].id"
    querystr2: "[]"

- name: "Reading tenants from <{{ management_base_url }}>"
  delegate_to: 127.0.0.1
  become: false
  uri:
    url: "{{ http_s }}://{{ management_base_url }}/api/v1/scopes/pmci/tags/latest/datasources/data-entity-tenants/query"
    method: GET
    headers:
      "Smardigo-User-Token": "{{ smardigo_auth_token_value }}"
    status_code: [200,201]
  register: pmci_tenants_results

- name: "Updating assigned tenants for each user"
  include_tasks: update_user_tenants.yml
  loop: '{{ pmci_users }}'
  loop_control:
    loop_var: current_user_id
