#!/bin/sh

datadir=/usr/share/alterator-office-server
ldapdbfile=slapd-office-server-user.conf

ldapdbconf=/etc/openldap/slapd-generated.conf
ldapmainconf=/etc/openldap/slapd.conf
ldapsysconf=/etc/sysconfig/ldap

rdelim='[[:space:]]\+'
wdelim=' '

po_domain="alterator-office-server"

. alterator-sh-functions
. shell-config
. shell-regexp

sure_ldapdbconf()
{
    [ -f "$ldapdbconf" ] && return

    if grep -qs "^SLAPDURLLIST=" "$ldapsysconf" ;then
    	sed -r "s,^SLAPDURLLIST=.*,SLAPDURLLIST=\"ldap://0.0.0.0\"," -i "$ldapsysconf"
    else
    	printf 'SLAPDURLLIST="ldap://0.0.0.0"\n' >>"$ldapsysconf"
    fi

    #sed -r '\,^include[[:space:]]+/etc/openldap/slapd-[a-zA-Z0-9-]+\.conf[[:space:]]*$, d' -i "$ldapmainconf"
		# enable samba3 schema
		sed -i -e "s,^[[:space:]]*#include[[:space:]]\+/etc/openldap/schema/samba3.schema,include\t/etc/openldap/schema/samba3.schema," "$ldapmainconf"
    printf 'include %s\n' "$ldapdbconf" >>"$ldapmainconf"

    cp -f "$datadir/$ldapdbfile" "$ldapdbconf"
    chmod 640 "$ldapdbconf"
    chown root:ldap "$ldapdbconf"
}

read_value()
{
    local value="$(shell_config_get "$ldapdbconf" "$1" "$rdelim")"

    value="${value#\"}"
    value="${value%\"}"
    printf '%s\n' "$value"
}

write_value()
{
    shell_config_set "$ldapdbconf" "$1" "\"$(quote_shell "$2")\"" "$rdelim" "$wdelim"
}

on_message()
{
	case "$in_action" in
		read)
			echo '('
			if [ -f "$ldapsysconf" ];then
			    sure_ldapdbconf
			    echo 'has_server #t '
			else
			    echo 'has_server #f '
			fi
			printf 'ldap_basedn "%s"\n' "$(read_value suffix)"
			echo ')'
			;;
		write)
			[ -n "$in_ldap_basedn" ] && write_value suffix "$in_ldap_basedn" && write_value rootdn "cn=ldaproot,$in_ldap_basedn"

			write_nop
			;;
		*)
			echo '#f'
			;;
	esac
}

message_loop
