#!/bin/sh

PASSWD_LDAP="files ldap"
SHADOW_LDAP="tcb files ldap"
GROUP_LDAP="files ldap"

PASSWD_LOCAL="files"
SHADOW_LOCAL="tcb files"
GROUP_LOCAL="files"

LDAP_CONFIG="/etc/nss_ldap.conf"

NSS_CONFIG="/etc/nsswitch.conf"

_()
{
    LANG=${in_language%%;*}.utf8 gettext "alterator-nsswitch" "$1"
}

read_ldap()
{
    [ -f "$LDAP_CONFIG" ] && sed -nr "s,^$1[[:space:]]([^[:space:]]+),\1,p" "$LDAP_CONFIG"
}

write_ldap()
{

    if grep -qs "^$1[[:space:]]" "$LDAP_CONFIG" ;then
	sed -r "s#^$1[[:space:]].*#$1 $2#" -i "$LDAP_CONFIG"
    else
	echo "$1 $2" >>"$LDAP_CONFIG"
    fi
}

list_profile()
{
    printf '("local" label "%s")' "`_ "local files"`"
    [ -n "$(find /$(getconf SLIB) -name 'libnss_ldap.*')" ] && printf '("ldap" label "%s")' "`_ "LDAP"`"
}

read_profile()
{
    if grep -qs "^passwd:[[:space:]]$PASSWD_LDAP" "$NSS_CONFIG";then
	echo "ldap"
    else
	echo "local"
    fi
}

write_profile()
{
    case "$1" in
	local)
	    sed "s,^passwd:.*,passwd: $PASSWD_LOCAL," -i "$NSS_CONFIG"
	    sed "s,^shadow:.*,shadow: $SHADOW_LOCAL," -i "$NSS_CONFIG"
	    sed "s,^group:.*,group: $GROUP_LOCAL," -i "$NSS_CONFIG"
	    ;;
	ldap)
	    sed "s,^passwd:.*,passwd: $PASSWD_LDAP," -i "$NSS_CONFIG"
	    sed "s,^shadow:.*,shadow: $SHADOW_LDAP," -i "$NSS_CONFIG"
	    sed "s,^group:.*,group: $GROUP_LDAP," -i "$NSS_CONFIG"
	    ;;
    esac
}

#turn off auto expansion
set -f

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

LDAP_URI="(ldap|ldapi|ldaps)://[a-z0-9.]+"

#comment host option to avoid conflict with uri
sed -r 's,^(host[[:space:]]),#\1,' -i "$LDAP_CONFIG"

on_message()
{
	case "$in_action" in
	    constraints)
		echo '('
		printf 'profile (label "%s")' "`_ "Database"`"
		printf 'ldap_uri (label "%s" match ("%s" "%s"))' \
		    "`_ "LDAP server"`" \
		    "$LDAP_URI" \
		    "`_ "should be ldap://host or ldapi://host or ldaps://host"`"
		printf 'ldap_basedn (label "%s")' "`_ "Base DN"`"
		echo ')'
		;;
	    list)
		echo '('
		[ "$in__objects" = "avail_profile" ] && list_profile
		echo ')'
		;;
	    read)
		echo '('
		local profile="$(read_profile)"

		printf 'profile "%s"' "$profile"
		printf 'ldap_uri "%s"\n' "$(read_ldap uri)"
		printf 'ldap_basedn "%s"\n' "$(read_ldap base)"
		echo ')'
		;;
	    write)
		[ -n "$in_profile" ] && write_profile "$in_profile"
	        [ -n "$in_ldap_uri" ] && write_ldap uri "$in_ldap_uri"
	        [ -n "$in_ldap_basedn" ] && write_ldap base "$in_ldap_basedn"
		echo '()'
		;;
	    *)
		echo '#f'
		;;
	esac
}

message_loop
