---

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

- name: "Deleting realm <{{ current_realm_name }}>"
  community.general.keycloak_realm:
    id: "{{ current_realm_name }}"
    realm: "{{ current_realm_name }}"
    auth_realm: "master"
    auth_client_id: "admin-cli"
    auth_username: "{{ keycloak_admin_username }}"
    auth_password: "{{ keycloak_admin_password }}"
    auth_keycloak_url: "{{ shared_service_url_keycloak }}/auth"
    state: absent
  tags:
    - always
  when:
    - keycloak_force_prune

- name: "Setup realm for {{ inventory_hostname }}"
  include_role:
    name: keycloak
    tasks_from: _configure_realm

- name: "Create realm users"
  include_role:
    name: keycloak
    tasks_from: _create_realm_groups

- name: "Create realm users"
  include_role:
    name: keycloak
    tasks_from: _create_realm_users

- name: "Create realm admin"
  include_role:
    name: keycloak
    tasks_from: _create_realm_admin

- name: "Create user group mappings"
  include_role:
    name: keycloak
    tasks_from: _configure_user_groupmembership_crud
  vars:
    realm_name: '{{ current_realm_name }}'
    bearer_token: '{{ access_token }}'
    username: '{{ item.username }}'
    destination_group: '{{ item.destination_group }}'
  loop: "{{ current_user_groupmembership | default([]) }}"
  loop_control:
    label: "{{ item.username }} >> {{ item.destination_group }}"

- name: "Create custom clientscope mappers"
  delegate_to: 127.0.0.1
  become: false
  community.general.keycloak_clientscope:
    auth_client_id: "admin-cli"
    auth_keycloak_url: "{{ shared_service_url_keycloak }}/auth"
    auth_realm: "master"
    auth_username: "{{ keycloak_admin_username }}"
    auth_password: "{{ keycloak_admin_password }}"
    name: "groups"
    realm: "{{ current_realm_name }}"
    protocol: "openid-connect"
    protocol_mappers:
      # add custom group mapper to avoid paths in group names
      - name: "groups"
        protocol: "openid-connect"
        protocolMapper: "oidc-group-membership-mapper"
        config:
          access.token.claim: true
          claim.name: "groups"
          full.path: false
          id.token.claim: true
          userinfo.token.claim: true
