---
- 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
  tags: [ 'ldap_server', 'ldap', 'ldap_conf' ]

- name: Restart apparmor
  service: name=apparmor state=restarted
  tags: [ 'ldap_server', 'ldap', 'ldap_conf' ]

- 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
  tags: [ 'ldap_server', 'ldap', 'ldap_conf' ]

- 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
  tags: [ 'ldap_server', 'ldap', 'ldap_conf' ]

- 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
  tags: [ 'ldap_server', 'ldap', 'ldap_conf' ]

- 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
  tags: [ 'ldap_server', 'ldap', 'ldap_conf' ]

- 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
  tags: [ 'ldap_server', 'ldap', 'ldap_conf' ]

- name: Finally set the admin password
  shell: ldapmodify -Q -Y EXTERNAL -H ldapi:/// -f /etc/ldap/adminpwd.ldif
  when: admin_pass_file is changed
  tags: [ 'ldap_server', 'ldap', 'ldap_conf' ]

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

- 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([]) }}'
  tags: [ 'ldap_server', 'ldap', 'ldap_conf' ]

- 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([]) }}'
  tags: [ 'ldap_server', 'ldap', 'ldap_conf' ]

- name: Install the default environment for slapd
  template: src=slapd-default.j2 dest=/etc/default/slapd owner=root group=root mode=0644
  tags: [ 'ldap_server', 'ldap', 'ldap_conf' ]