#!/bin/bash

#
# Copyright (C) 2008 Ivo van Doorn <IvDoorn@gmail.com>
#
# This script can be used to dump the contents of the rt2x00
# registers which are found in debugfs.
#

#
# regexp matches for mac80211 interfaces and the rt2x00 drivers
#
MAC80211_REGEXP='phy*'
RT2X00_REGEXP='rt[0-9]*'

#
# Find where debugfs is mounted, when it isn't we might as well
# bail out immediately.
#
DEBUG_ROOT=`grep debugfs /proc/mounts | cut -d' ' -f2 | head -n 1`
if [ -z ${DEBUG_ROOT} ]; then
	echo "debugfs not mounted!"
	exit 1
fi

#
# When no argument is given, we are looping over all mac80211 interfaces
# which contain a valid rt2x00 entry (a folder which matches RT2X00_REGEXP).
# If an argument is given, we check if it is a directory, if that is the case,
# we try to use that as root for the register dump. Otherwise we check the
# argument against MAC80211_REGEXP and RT2X00_REGEXP to limit the number
# of interfaces to check. When the argument matches MAC80211_REGEXP we only
# need to loop that interface, while when it matches RT2X00_REGEXP we must
# loop over all interfaces for that driver.
#
if [ -z ${1} ]; then
	DEBUG_ROOT_RT2X00=${DEBUG_ROOT}/ieee80211/${MAC80211_REGEXP}/${RT2X00_REGEXP}/
elif [ -d ${1} ]; then
	DEBUG_ROOT_RT2X00=${1}/
elif [ `expr "${1}" : "${RT2X00_REGEXP}"` -gt 0 ]; then
	DEBUG_ROOT_RT2X00=${DEBUG_ROOT}/ieee80211/${MAC80211_REGEXP}/${1}/
elif [ `expr "${1}" : "${MAC80211_REGEXP}"` -gt 0 ]; then
	DEBUG_ROOT_RT2X00=${DEBUG_ROOT}/ieee80211/${1}/${RT2X00_REGEXP}/
else
	echo "Unknown argument: ${1}"
fi

function doPrint()
{
	REGISTER_DIR=${1}/register
	CHIPSET_FILE=${1}/chipset
	DRIVER_FILE=${1}/driver
	FLAGS_FILE=${1}/dev_flags

	echo -n "kernel: "
	uname -r
	cat ${DRIVER_FILE}
	echo -n "dev_flags: "
	cat ${FLAGS_FILE}
	cat ${CHIPSET_FILE}

	#
	# All register statistics is formatted as:
	# name	base	words	wordsize
	#
	while read line
	do
		IFS=":"
		DATA=( $line )

		echo -e "\n${DATA[0]}"
		for (( x=0; x<${DATA[1]}; x=x+1 )); do
			echo $x > "${REGISTER_DIR}/${DATA[0]}_offset"
			echo -n $x :
			cat "${REGISTER_DIR}/${DATA[0]}_value"
		done
	done < <(awk --posix '/^[a-zA-Z]+(\t[0-9]+){3}$/ { print $1":"$3 }' ${CHIPSET_FILE})

	echo -e "\n"
}

for entry in `ls -d1 ${DEBUG_ROOT_RT2X00}`; do
	doPrint ${entry}
done
