#!/bin/bash

# olpc-mesh-0.2
# Copyright (C) 2008 Giannis Galanis <echo gxlxnis@lxptop.org | sed s/x/a/>

# 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.

list() {
	echo -e "          DA                  RA        ok  cost dir rate hop ttl exp(min) snr     precursor"
	for i in `seq 1 200`
	do 
		x=`iwpriv msh0 fwt_list $i`
		echo $x|grep null>/dev/null && break
		printf %2d $i
		echo $x|grep -v null|sed 's/^.*list: //'|sed s/00:00.*$//|awk '
			{printf " "$1"  "$2"  "$3}
			{printf "%5d",$4}
			{printf "   "$5}
			{printf "%5d",$6}
			{printf "   "$9"   "$10" "}
			{printf "%7d", $11/60000}
			{print "    "$13"  "$14}'
	done|sort
}

replace () {
	for i in `seq 1 \`cat $file|wc -l\``
	do
		line=`awk "NR==$i" $file`

		mac=`echo ${line:0:17}|tr '[A-Z]' '[a-z]'`
		name=`echo $line|sed "s/^.*:...//"`

		empty="                  "
		let space=17-${#name}
		let space1=$space/2
		let space2=$space-$space1

		name=`echo -n "${empty:0:$space1}";echo -n "$name";echo "${empty:0:$space2}"`

		cat tmp1|sed "s/$mac/$name/g" > tmp2
		mv tmp2 tmp1
	done
cat tmp1
rm tmp1
}

help () {
cat << EOF
Usage: olpc-mesh [-t FILE]
Display the mesh forwarding tables in a readable manner.

Option:
  
  -t FILE     : Use a MAC/Nick table to replace each address with its Nick.
                The <FILE> must be in the form:
                00:17:C4:XX:XX:XX Nick 1
                00:17:C4:XX:XX:XX Nick 2
                ...

                You may populate the file from the current neighborhood with
		olpc-xos -mac > FILE

EOF
exit
}

echo " $@ "|grep -E "( -h | --help )" > /dev/null && help

[ "$1" = "-t" ] && [ -f "$2" ] && file="$2" && list > tmp1 && replace
[ ! "$1" = "-t" ] || [ ! -f "$2" ] && list 

