#!/bin/sh

po_domain="alterator-auth"
ldapfile="/etc/pam_ldap.conf"
ldap_uri_re='(ldap|ldapi|ldaps)://[a-z0-9.]+'
rdelim='[[:space:]]\+'
wdelim=' '

. alterator-sh-functions
. shell-config

#turn off auto expansion
set -f

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

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

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


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

on_message()
{
	case "$in_action" in
	    constraints)
		echo '('
		printf 'profile (label "%s")' "`_ "Auth type"`"
		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="$(/usr/sbin/control system-auth)"

		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" ] && /usr/sbin/control system-auth "$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
