---
# Reset both Database and Configuration Admin passwords in LDAP via LDAPI

- name: "Query available LDAP databases"
  shell: |
    docker exec {{ openldap_name }} \
      ldapsearch -Y EXTERNAL -H ldapi:/// -LLL -b cn=config "(olcDatabase=*)" dn
  register: ldap_databases

- name: "Determine data backend DN (mdb)"
  set_fact:
    data_backend_dn: >-
      {{ ldap_databases.stdout_lines
         | select('search','^dn: olcDatabase=.*mdb')
         | map('regex_replace','^dn: ','')
         | list
         | first }}

- name: "Determine config backend DN"
  set_fact:
    config_backend_dn: >-
      {{ ldap_databases.stdout_lines
         | select('search','^dn: olcDatabase=\{[0-9]+\}config,cn=config$')
         | map('regex_replace','^dn: ','')
         | list
         | first }}

- name: "Generate hash for Database Admin password"
  shell: |
    docker exec {{ openldap_name }} \
      slappasswd -s "{{ ldap.bind_credential }}"
  register: database_admin_pw_hash

- name: "Reset Database Admin password in LDAP (olcRootPW)"
  shell: |
    docker exec -i {{ openldap_name }} ldapmodify -Y EXTERNAL -H ldapi:/// <<EOF
    dn: {{ data_backend_dn }}
    changetype: modify
    replace: olcRootPW
    olcRootPW: {{ database_admin_pw_hash.stdout }}
    EOF

- name: "Generate hash for Configuration Admin password"
  shell: |
    docker exec {{ openldap_name }} \
      slappasswd -s "{{ applications | get_app_conf(application_id, 'credentials.administrator_password', True) }}"
  register: config_admin_pw_hash

- name: "Reset Configuration Admin password in LDAP (olcRootPW)"
  shell: |
    docker exec -i {{ openldap_name }} ldapmodify -Y EXTERNAL -H ldapi:/// <<EOF
    dn: {{ config_backend_dn }}
    changetype: modify
    replace: olcRootPW
    olcRootPW: {{ config_admin_pw_hash.stdout }}
    EOF