---

# Parameters:
#   playbook inventory
#     realm_name := name of the realm to delete the client from
#     client_name := client name to delete

- name: "Authenticate with Keycloak server"
  uri:
    url: "{{ keycloak_server_url }}/auth/realms/master/protocol/openid-connect/token"
    method: POST
    body_format: form-urlencoded
    body: 'username={{ keycloak_admin_username }}&password={{ keycloak_admin_password }}&client_id=admin-cli&grant_type=password'
  retries: 5
  delay: 5
  register: keycloak_authentication
  delegate_to: 127.0.0.1
  become: false

- name: "Read clients from realm {{ realm_name }}"
  uri:
    url: "{{ keycloak_server_url }}/auth/admin/realms/{{ realm_name }}/clients"
    method: GET
    headers:
      Authorization: "Bearer {{ keycloak_authentication.json.access_token }}"
    status_code: [200, 404]
  register: realm_clients
  delegate_to: 127.0.0.1
  become: false

- name: "Read clients from realm {{ realm_name }}"
  debug:
    msg: "{{ realm_clients }}"
  delegate_to: 127.0.0.1
  become: false
  when:
   - debug

- name: "Save clients from realm as variable (fact) - 200"
  set_fact:
    realm_clients_json: "{{ realm_clients.json }}"
  delegate_to: 127.0.0.1
  become: false
  when:
    - realm_clients.status == 200

- name: "Save clients from realm as variable (fact) - 404"
  set_fact:
    realm_clients_json: []
  delegate_to: 127.0.0.1
  become: false
  when:
    - realm_clients.status == 404

- name: "Saving client <{{ client_name }}> from realm <{{ realm_name }}>"
  set_fact:
    realm_client_id: "{{ realm_clients_json | json_query(jmesquery) | first | default('-') }}"
  vars:
    jmesquery: '[?clientId==`{{ client_name }}`].id'
  delegate_to: 127.0.0.1
  become: false

- name: "Printing client <{{ client_name }}> from realm <{{ realm_name }}>"
  debug:
    msg: "{{ realm_client_id }}"
  delegate_to: 127.0.0.1
  become: false
  when:
   - debug

- name: "Deleting client <{{ client_name }}> for realm <{{ realm_name }}>"
  uri:
    url: "{{ keycloak_server_url }}/auth/admin/realms/{{ realm_name }}/clients/{{ realm_client_id }}"
    method: DELETE
    body_format: json
    headers:
      Authorization: "Bearer {{ keycloak_authentication.json.access_token }} "
    status_code: [204]
  when:
        realm_client_id != '-'
  changed_when: True
  delegate_to: 127.0.0.1
  become: false
