#!/bin/sh

#common part
po_domain="alterator-auth"
alterator_api_version=1
ldap_uri_re='^(ldap|ldapi|ldaps)://[.a-zA-Z0-9_-]+$'
rdelim='[[:space:]]\+'
wdelim=' '

. alterator-sh-functions
. shell-config
. shell-quote

#turn off auto expansion
set -f

host_2_dn()
{
    local host="$1" ; shift
    host="$(echo $host|sed -e "s/^/dc=/"|sed -e "s/\./,dc=/g")"
    echo "$host"
}

list_domain()
{
	local __ prefix ip txt role domain

    write_enum_item "local" "$(_ "local")"
	avahi-browse -prtk _server._tcp 2>/dev/null|
		while IFS=';' read prefix __ __ __ __ __ __ ip __ txt; do
			[ "$prefix" = "=" ] || continue
			role="$(txt_record role "$txt")"
			[ "$role" = "master" ] || continue
			domain="$(txt_record domain "$txt")"
            write_enum_item "$domain" "$domain ($ip)"
		done
    write_enum_item "custom" "$(_ "custom")"
}

txt_record()
{
	echo "$2" |
		sed -n "s/\(^\|.*[[:space:]]\)\"$(quote_sed_regexp "$1")=\([^\"]*\)\".*/\2/p"
}

dn_2_host()
{
    local dn="$1"
    local host=

    echo "$dn"|sed -e 's/^dc=//i'|sed -e 's/,dc=/\./g'
}

read_current()
{
    local data="$(/usr/sbin/system-auth status)"
    local status="$(echo "$data"|cut -f1 -d' ')"
    local dn

    [ "$status" = "krb5" ] && dn="$(echo "$data"|cut -f2 -d' ')" &&  dn_2_host "$dn" && return

    echo "not set"
}

on_message()
{
	case "$in_action" in
	    type)
        write_type_item domain_name hostname
        write_type_item domain hostname
		;;
	    list)
		[ "$in__objects" = "avail_domain" ] && list_domain
		;;
	    read)
        write_string_param current_domain "$(read_current)"

		;;
	    write)

        [ -z "$in_domain" ] && fatal "$(_ "Domain not set")"

        case "$in_domain" in
            local)
                /usr/sbin/system-auth write local
            ;;
            custom)
                [ -z "$in_domain_name" ] && fatal "$(_ "Domain not set")"
                /usr/sbin/system-auth write krb5 "$(host_2_dn "$in_domain_name")" ldap://ldap."$in_domain_name"
            ;;
            *)
                /usr/sbin/system-auth write krb5 "$(host_2_dn "$in_domain")" ldap://ldap."$in_domain"
            ;;
        esac

        write_nop
		;;
	esac
}

message_loop
