#!/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"


ldapfile=
ldapfile1="/etc/nss_ldap.conf"
ldapfile2="/etc/nss-ldapd.conf"
nssfile="/etc/nsswitch.conf"

[ -f "$ldapfile1" ] && ldapfile="$ldapfile1"
[ -f "$ldapfile2" ] && ldapfile="$ldapfile2"

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

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

write_ldap()
{

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

list_profile()
{
    printf '("local" label "%s")' "`_ "local files"`"
    [ -n "$ldapfile" ] && printf '("ldap" label "%s")' "`_ "LDAP"`"
}

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

write_profile()
{
    case "$1" in
	local)
	    sed "s,^passwd:.*,passwd: $passwd_local," -i "$nssfile"
	    sed "s,^shadow:.*,shadow: $shadow_local," -i "$nssfile"
	    sed "s,^group:.*,group: $group_local," -i "$nssfile"
	    ;;
	ldap)
	    sed "s,^passwd:.*,passwd: $passwd_ldap," -i "$nssfile"
	    sed "s,^shadow:.*,shadow: $shadow_ldap," -i "$nssfile"
	    sed "s,^group:.*,group: $group_ldap," -i "$nssfile"
	    ;;
    esac
}

#turn off auto expansion
set -f

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

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

#initial hacks

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

#fix default timeouts
write_ldap nss_reconnect_tries 1
write_ldap nss_reconnect_maxconntries 1

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
