#
# Common shell routines for testing Avahi service discovery
# Copyright (c) 2013-2014 Red Hat.
#

# get standard environment, filters and checks
. ./common.product
. ./common.filter
. ./common.check

avahi_notrun_checks()
{
    _get_libpcp_config
    $service_discovery || _notrun "No support for service discovery"

    # Is avahi-browse installed?
    which avahi-browse >/dev/null 2>&1 || _notrun avahi-browse is not installed

    # Is the avahi-daemon installed and running?  (maybe /sbin or /usr/sbin)
    avahi-daemon --check 2>/dev/null || _notrun avahi-daemon is not available
}

avahi_cleanup()
{
    cd $here
    $sudo $signal -a "$service" >/dev/null 2>&1
    rm -f $tmp.*
}

avahi_service()
{
    _stop_auto_restart $service
    $sudo "$PCP_RC_DIR/$service" restart >>$here/$seq.full 2>&1
    _restore_auto_restart $service
}

avahi_verify()
{
    msg="$@"

    [ "X$msg" = "X" ] && msg="Verify $service avahi service advertising"
    echo $msg | tee -a $here/$seq.full

    # strip any domain part ... e.g. if hostname is vm08.localdomain,
    # avahi reports this as vm08.local
    # look for a line like this ...
    # = eth0 IPv4 PCP pmproxy on vm04.localdomain _pmproxy._tcp local
    # + eth0 IPv6 PCP pmproxy on vm30 _pmroxy._tcp local
    #
    hostname=`hostname | sed -e 's/\..*//'`
    echo "hostname=$hostname" >>$here/$seq.full
    echo "avahi-browse -rt -d local _$service._tcp" >> $here/$seq.full
    avahi-browse -rt -d local "_$service._tcp" > $tmp.out
    # sometimes we need a fair bit of time for avahi to register
    for i in 0.1 0.3 1 2 3
    do
	[ -s $tmp.out ] && break
	pmsleep $i
	avahi-browse -rt -d local "_$service._tcp" > $tmp.out
    done
    cat $tmp.out | \
	tee -a $here/$seq.full | \
	sed -n \
	    -e '/ '"$hostname"'[ .]/{
s/  */ /g
s/'"$hostname"'[^ ]*/HOSTNAME/
s/[=+] [^ ]* /. <interface> /
s/ IPv[46] / <protocol> /
s/ \#[0-9] / /
p
q
}'

}
