#!/bin/sh

po_domain="alterator-openldap"
alterator_api_version=1

. alterator-sh-functions
. shell-config


SLAPD_CONF_DIR="/etc/openldap"
SLAPD_CONF="$SLAPD_CONF_DIR/slapd.conf"
LDAP_SYSCONFIG="/etc/sysconfig/ldap"
LDAP_CONF="$SLAPD_CONF_DIR/ldap.conf"
CERT_FILE="/etc/openldap/ssl/slapd.pem"

ldap_read_sysconfig()
{	local url
	url="$(shell_config_get "$LDAP_SYSCONFIG" SLAPDURLLIST)"
	[ "${url/ldap:\/\//}" != "$url" ] && write_bool_param 'port_ldap' 'yes'
	[ "${url/ldaps:\/\//}" != "$url" ] && write_bool_param 'enable_ldaps'  'yes'
	[ "${url/\/\/localhost\/}" != "$url" ] && write_bool_param 'localhost' 'yes'
}

# Enables or disables the specified schema in the slapd configuration.
# args: schema-name flag
toggle_schema()
{
	echo "[openldap] Enable schema '$1'" 1>&2
	sed -i -e "s,^[[:space:]]*#include[[:space:]]\+/etc/openldap/schema/$1.schema,include\t/etc/openldap/schema/$1.schema," "$SLAPD_CONF"
}


#args
write_tls()
{
	if [ "$in_enable_ldaps" = "#t" ] ;then
		for i in TLSCACertificateFile TLSCertificateFile TLSCertificateKeyFile;do
			sed -i -e "s|^#$i $CERT_FILE$|$i $CERT_FILE|" $SLAPD_CONF
		done
	else
		for i in TLSCACertificateFile TLSCertificateFile TLSCertificateKeyFile;do
			sed -i -e "s|^$i $CERT_FILE$|#$i $CERT_FILE|" $SLAPD_CONF
		done
	fi
}

on_message()
{
    echo "[openldap] Processing action '$in_action' on object '$in__objects' and name '$in_name' ldaps=$in_enable_ldaps" 1>&2
    case "$in_action" in
	list)
	    echo '('
	    echo ')'
	    ;;
	read)
	    echo '('
	    case "$in__objects" in
		/)
		    ldap_read_sysconfig
		    ;;
	    esac
	    echo ')'
	    ;;
	write)
	    case "$in__objects" in
		/)
		    local host=""
		    local url=""
		    if [ "$in_localhost" = "#t" ]; then
			host="localhost"
		    fi
		    if [ "$in_port_ldap" = "#t" ]; then
			url="$url ldap://$host/"
		    fi
		    if [ "$in_enable_ldaps" = "#t" ]; then
			url="$url ldaps://$host/"
		    fi
		    	write_tls
		    shell_config_set "$LDAP_SYSCONFIG" SLAPDURLLIST "\"'$url'\""
		    shell_config_set "$LDAP_CONF" URI "$url" ' ' ' '
		    toggle_schema "samba3" 
		    ;;
	    esac
	    service slapd condrestart 1>&2
	    echo '('
	    echo ')'
	    ;;
    esac
}

message_loop
