#!/bin/bash

# olpc-xos-0.3
# Copyright (c) 2007, 2008 Giannis Galanis <echo gxlxnis@lxptop.org | sed s/x/a/g>

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

help () {
cat <<EOF
Usage: olpc-xos [-c] [-avahi|-sugar|-mac]

  -c       run continuously
  
  -sugar   display the XOs seen by Presence Service
  -avahi   display the XOs seen by Avahi
  -mac     display the XOs seen by Avahi in "00:17:C4:XX:XX:XX Nick" form

EOF
exit
}

avahilist () {
tmp=`mktemp`
avahi-browse -t -r _presence._tcp &> $tmp
while read line
do
	echo -n "$line"|awk '/^=/ {printf $4"\t"}'
	echo -n "$line"|awk '/address =/ {printf $3"\t"}'|tr -d '[]'
	echo "$line"|grep "txt ="|sed 's/^.*nick=//'|sed s/\".*$//
	echo "$line"|awk '/Failed/ {print "Failed:"$5}'
done<$tmp |sort -k3
}

maclist () {
avahilist|grep -v ^Fai|sed 's/^........@xo-\(..\)-\(..\)-\(..\)/00:17:C4:\1:\2:\3/'|awk '{$2="";print}'
}

sugarlist () {
	sugar-xos | sort -k2
}

display () {
	echo -n "Time   : "
	date +%H:%M:%S
	
	f=`cat "$tmp1"|grep ^Fail|wc -l` 
	echo -n "Total  : "
	echo $((`cat "$tmp1"|wc -l`-$f))
	
	[ $f -gt 0 ] && echo "Failed : $f"
	
	echo
	cat "$tmp1"
	[ "$cont" == 1 ] && echo --------------------
}

tmp1=`mktemp`
tmp2=`mktemp`

getlist=sugarlist
echo " $@ "|tr -d "-"|grep -E "( h | help )" > /dev/null && help
echo " $@ "|tr -d "-"|grep "avahi" > /dev/null && getlist=avahilist
echo " $@ "|tr -d "-"|grep "sugar" > /dev/null && getlist=sugarlist
echo " $@ "|tr -d "-"|grep "mac" > /dev/null && maclist && exit
echo " $@ "|grep "\-c" > /dev/null && cont=1

$getlist > "$tmp1"
display

[ "$cont" == 1 ] &&
while true
do
	$getlist > "$tmp2"
	[ -n "`comm -3 $tmp1 $tmp2`" ] && mv $tmp2 $tmp1 && display
done 
