#!/bin/sh

po_domain="alterator-nsswitch"

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"

ldap_uri_re="(ldap|ldapi|ldaps)://[a-z0-9.]+"
rdelim='[[:space:]]\+'
wdelim=' '

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

#turn off auto expansion
set -f

. alterator-sh-functions
. shell-config

read_ldap()
{
    shell_config_get "$ldapfile" "$1" "$rdelim"
}

write_ldap()
{
    shell_config_set "$ldapfile" "$1" "$2" "$rdelim" "$wdelim"
}

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
}

#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_re" \
		    "`_ "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 "$(string_quote_remove "$in_ldap_basedn")"
		write_nop
		;;
	    *)
		echo '#f'
		;;
	esac
}

message_loop
