#!/bin/bash
#Filename: openldap-server.sh

# Export Path
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin
export PATH

# Check Root
if [ $(id -u) != "0" ]; then
    echo "Error: Please use root role to install me!"
    exit 1
fi

# Define Variable
adm_pwd="123456"

function install() {
    yum -y install openldap openldap-clients openldap-servers migrationtools
    slappasswd -s ${adm_pwd} -n >/etc/openldap/password

    # Create keys
    cd /etc/openldap/certs
    openssl req -new -x509 -nodes -out /etc/openldap/certs/cert.pem -keyout /etc/openldap/certs/priv.pem -days 365
    chown ldap:ldap *.pem
    chmod 600 priv.pem
    
    # Copy LDAP-DB
    if [ ! -e  /var/lib/ldap/DB_CONFIG ];then
        cp /usr/share/openldap-servers/DB_CONFIG.example /var/lib/ldap/DB_CONFIG
    fi

    slaptest

    cd /var/lib/ldap/
    chown ldap:ldap ./ -R

    systemctl start slapd.service
    systemctl enable slapd.service

    # Set ldap-log
    echo "local4.*   /var/log/ldap.log" >> /etc/rsyslog.conf
    
    systemctl restart rsyslog

     cd /etc/openldap/schema/

    ldapadd -Y EXTERNAL -H ldapi:/// -D "cn=config" -f cosine.ldif
    ldapadd -Y EXTERNAL -H ldapi:/// -D "cn=config" -f nis.ldif

    cd /usr/local/src
    wget http://down.vqiu.cn/resource/RHEL_7/changes.ldif;ldapmodify -Y EXTERNAL -H ldapi:/// -f ./changes.ldif
    wget http://down.vqiu.cn/resource/RHEL_7/base.ldif;ldapadd -x -w ${adm_pwd} -D cn=Manager,dc=example,dc=com -f  ./base.ldif

}
