# https://wiki.debian.org/LDAP/PAM
# https://arthurdejong.org/nss-pam-ldapd/setup
---
  - name: set up pam ldap authentication
    tags: ldap-pam
    become: true
    vars:
      hosttype: "{{ inventory_hostname | regex_search('(devel)|(prod)|(localdev)') }}"

    block:
    - name: ensure libpam-ldapd package is installed
      ansible.builtin.apt:
        name: libpam-ldapd
        state: present

    # Most of the files and configuration in pam.d/common-* are done by the
    # package libpam-ldapd
    - name: update common-session
      ansible.builtin.lineinfile:
        path: "/etc/pam.d/common-session"
        line: "session required	pam_mkhomedir.so"

    - name: update nslcd.conf
      block:
      - name: insert ldap uri
        ansible.builtin.lineinfile:
          path: "/etc/nslcd.conf"
          regexp: "^uri\\s+\\S*"
          line: "uri ldap://127.0.0.1:389"

      - name: insert ldap base
        ansible.builtin.lineinfile:
          path: "/etc/nslcd.conf"
          regexp: "^base\\s+\\S*"
          line: "base ou=file,{{ ldap_basedn }}"

      - name: insert ldap version
        ansible.builtin.lineinfile:
          path: "/etc/nslcd.conf"
          regexp: "^ldap_version\\s+\\S*"
          line: "ldap_version 3"

      - name: insert ldap binddn
        ansible.builtin.lineinfile:
          path: "/etc/nslcd.conf"
          regexp: "^binddn\\s+\\S*"
          line: "binddn cn=fileAccountReader,ou=Manager,ou=file,{{ ldap_basedn }}"

      - name: insert ldap bindpw
        ansible.builtin.lineinfile:
          path: "/etc/nslcd.conf"
          regexp: "^bindpw\\s+\\S*"
          line: "bindpw {{ ldap_fileAccountReader_pw }}"
        diff: false

    - name: update nsswitch.conf
      block:
      - name: insert ldap as service for passwd
        ansible.builtin.lineinfile:
          path: "/etc/nsswitch.conf"
          regexp: "^passwd:\\s+files\\.*"
          line: "passwd:  files systemd ldap"

      - name: insert ldap as service for group
        ansible.builtin.lineinfile:
          path: "/etc/nsswitch.conf"
          regexp: "^group:\\s+files\\.*"
          line: "group:  files systemd ldap"

      - name: insert ldap as service for shadow
        ansible.builtin.lineinfile:
          path: "/etc/nsswitch.conf"
          regexp: "^shadow:\\s+files\\.*"
          line: "shadow:  files systemd ldap"

    notify: restart-nslcd
