#!/bin/sh

LDAP_CONFIG=/etc/openldap/slapd-hpc-user.conf

MAIN_CONFIG=/etc/openldap/slapd.conf
SYS_CONFIG=/etc/sysconfig/ldap

#initial hacks
init_value()
{
    if grep -qs "^SLAPDURLLIST=" "$SYS_CONFIG" ;then
	sed -r "s,^SLAPDURLLIST=.*,SLAPDURLLIST=\"ldap://$(hostname)\"," -i "$SYS_CONFIG"
    else
	printf 'SLAPDURLLIST="ldap://%s"\n' $(hostname) >>"$SYS_CONFIG"
    fi

    sed -r '\,^include[[:space:]]+/etc/openldap/slapd-[a-zA-Z0-9-]+\.conf[[:space:]]*$, d' -i "$MAIN_CONFIG"
    printf 'include %s\n' "$LDAP_CONFIG" >>"$MAIN_CONFIG"
}

read_value()
{
    local name="$1";shift
    local value=

    value="$(sed -nr "s,^$name[[:space:]]+,,p" "$LDAP_CONFIG")"
    [ -n "$value" ] || return 0

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

write_value()
{
    local name="$1";shift
    local value="$(echo "$1"|simple_quote)";shift

    [ ! -s "$LDAP_CONFIG" ] || sed -r "/$name[[:space:]]/ d" -i "$LDAP_CONFIG"
    printf '%s "%s"\n' "$name" "$value" >> "$LDAP_CONFIG"
}

. /usr/share/alterator/build/backend3.sh

on_message()
{
	case "$in_action" in
		init)
			init_value
			echo '()'
			;;
		read)
			echo '('
			printf 'ldap_basedn "%s"\n' "$(read_value suffix)"
			printf 'ldap_rootdn "%s"\n' "$(read_value rootdn)"
			echo ')'
			;;
		write)
			[ -n "$in_ldap_basedn" ] && write_value suffix "$in_ldap_basedn"
			[ -n "$in_ldap_rootdn" ] && write_value rootdn "$in_ldap_rootdn"
			[ -n "$in_ldap_rootpw" ] && write_value rootpw "$in_ldap_rootpw"

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

message_loop
