---
- block: 
  - name: Install the apparmor additional configuration if we are going to use letsencrypt
    copy: src=usr.sbin.slapd.apparmor dest=/etc/apparmor.d/local/usr.sbin.slapd force=yes 
    register: slapd_apparmour
    when: openldap_letsencrypt_managed

  - name: Restart apparmor
    service: name=apparmor state=restarted

  - name: Install the ldif file needed to change the BASE DN and the Root DN
    template: src=base-dn.ldif.j2 dest=/etc/ldap/schema/base-dn.ldif owner=root group=root mode=0400
    register: base_dn_ldif

  - name: Change the Base DN and Root DN
    shell: ldapmodify -Q -Y EXTERNAL -H ldapi:/// -f /etc/ldap/schema/base-dn.ldif
    when: base_dn_ldif is changed

  - name: Generate the local admin password
    shell: slappasswd -h {SSHA} -s {{ slapd_admin_pwd }} > /root/.slapdadmin ; chmod 400 /root/.slapdadmin
    args:
      creates: /root/.slapdadmin
    when: slapd_admin_pwd is defined
    register: admin_pass_file

  - name: Copy the ldif template to set the admin password
    template: src=adminpwd.ldif.j2 dest=/etc/ldap/adminpwd_ldif.tmpl
    when: slapd_admin_pwd is defined

  - name: Create the ldif file to set the admin password
    shell: export ADMIN_PASS=$( cat /root/.slapdadmin ); sed -e "s/@ADMINPWD@/${ADMIN_PASS}/" /etc/ldap/adminpwd_ldif.tmpl > /etc/ldap/adminpwd.ldif ; chmod 400 /etc/ldap/adminpwd.ldif
    when: slapd_admin_pwd is defined

  - name: Finally set the admin password
    shell: ldapmodify -Q -Y EXTERNAL -H ldapi:/// -f /etc/ldap/adminpwd.ldif
    when: admin_pass_file is changed

  - name: Copy the monitor ldif file
    template: src={{ item }}.j2 dest=/etc/ldap/schema/{{ item }}
    with_items: '{{ openldap_base_schemas | default([]) }}'

  - name: Install some default schemas
    shell: ldapadd -Q -Y EXTERNAL -H ldapi:/// -f /etc/ldap/schema/{{ item }} ; touch /etc/ldap/schema/.{{ item }}.installed
    args:
      creates: '/etc/ldap/schema/{{ item }}.installed'
    with_items: '{{ openldap_base_schemas | default([]) }}'

  - name: Install some additional schemas
    shell: ldapadd -Q -Y EXTERNAL -H ldapi:/// -f /etc/ldap/schema/{{ item }} ; touch /etc/ldap/schema/.{{ item }}.installed
    args:
      creates: '/etc/ldap/schema/{{ item }}.installed'
    with_items: '{{ openldap_additional_schemas | default([]) }}'

  - name: Install the default environment for slapd
    template: src=slapd-default.j2 dest=/etc/default/slapd owner=root group=root mode=0644
    
  - name: Install the DB_CONFIG settings
    template: src=DB_CONFIG.j2 dest=/var/lib/ldap/DB_CONFIG owner=openldap group=openldap mode=0644

  tags: [ 'ldap_server', 'ldap', 'ldap_conf' ]