---
- name: Install slapd
  apt:
    name:
      - ldap-utils
      - libio-socket-ssl-perl
      - slapd
    update_cache: true
    install_recommends: false
  register: apt_result
  retries: 3
  until: apt_result is succeeded

# Since we can't apply same updates to the LDAP server,
# we create at the end of the deployment a file which
# indicates that the replica is installed.
# If this file is still present, then we don't redeploy
# the reploy. If it was deleted or missing, then we
# rebuild the replica.
- name: Check if installation was done
  stat:
    path: /var/lib/slapd/.delete_me_to_reset_ldap_configuration
  register: installation

- name: Stop slapd
  when: not installation.stat.exists
  systemd:
    name: slapd
    state: stopped

- name: Delete old slapd configuration and data
  when: not installation.stat.exists
  file:
    path: '{{ item }}'
    state: absent
  loop:
    - /etc/ldap/slapd.d
    - /var/lib/ldap

- name: Create slapd configuration and data directory
  file:
    path: '{{ item }}'
    state: directory
    owner: openldap
    group: openldap
    mode: 0700
  loop:
    - /etc/ldap/slapd.d
    - /var/lib/ldap

- name: Copy ldif files
  template:
    src: 'ldap/{{ item }}.ldif.j2'
    dest: '/var/lib/slapd/{{ item }}.ldif'
    owner: openldap
    group: openldap
    mode: 0600
  loop:
    - db
    - schema
    - consumer_simple_sync
    - certinfo

- name: Initialize re2o-ldap schema
  when: not installation.stat.exists
  shell: slapadd -n 0 -l /var/lib/slapd/schema.ldif -F /etc/ldap/slapd.d/
  become_user: openldap

- name: Initialize re2o-ldap database
  when: not installation.stat.exists
  shell: slapadd -n 1 -l /var/lib/slapd/db.ldif
  become_user: openldap

- name: Start slapd
  when: not installation.stat.exists
  systemd:
    name: slapd
    state: started

- name: Enable data replication
  when: not installation.stat.exists
  shell: ldapadd -Q -Y EXTERNAL -H ldapi:/// -f /var/lib/slapd/consumer_simple_sync.ldif

# LDAPS configuration
- name: Copy TLS certificate
  template:
    src: "ldap/{{ item }}.j2"
    dest: "/etc/ldap/{{ item }}"
    owner: openldap
    group: openldap
    mode: 0600
  loop:
    - ldap.pem
    - ldap.key

- name: Load TLS certificates
  when: not installation.stat.exists
  shell: ldapmodify -Y EXTERNAL -H ldapi:/// -f /var/lib/slapd/certinfo.ldif

- name: Enable LDAPS
  lineinfile:
    path: /etc/default/slapd
    regexp: '^SLAPD_SERVICES='
    line: 'SLAPD_SERVICES="ldap:/// ldaps:/// ldapi:///"'
  notify: Restart slapd
  check_mode: false

- name: Touch installation marker
  when: not installation.stat.exists
  file:
    path: /var/lib/slapd/.delete_me_to_reset_ldap_configuration
    state: touch
    owner: root
    group: root
    mode: 0600