#!/bin/bash
# Collect diagnostic information and create a tar.gz archive
TMPDIR=/tmp/diagnostics

mkdir -p $TMPDIR


if [ "$TMPDIR" == "" ]; then
 exit 1
else
 touch $TMPDIR/dummy; rm -R $TMPDIR/*
fi

function run_command {

	TMPFILE=$TMPDIR/$1
	shift
	TITLE=$1
	shift
	if [ "$TITLE" == "!" ]; then
	TITLE=$*
	fi
	echo "===============================================================================" >> $TMPFILE
	echo $TITLE >> $TMPFILE
	echo "===============================================================================" >> $TMPFILE
	date >> $TMPFILE
	echo ">>>" >> $TMPFILE
	if [ "$1" != "" ]; then
		$* >> $TMPFILE
	else
		cat >> $TMPFILE
	fi
	echo "<<<" >> $TMPFILE
	echo "" >> $TMPFILE

}

function show_file {

	OUTFILE=$1; shift
	TITLE=$1; shift
	FILENAME=$1; shift
	if [ -e $FILENAME ]; then
		run_command $OUTFILE "$TITLE" cat $FILENAME
	else
		echo "File [$FILENAME] does not exist" | run_command $OUTFILE $TITLE
	fi

}
		
show_file device "Device Version" /device_version
show_file device "Partitions" /proc/partitions
show_file device "CPU Info" /proc/cpuinfo
show_file device "Devices" /proc/devices

for i in `ls /*_info`
do
 cp $i $TMPDIR
done

cp /mnt/flash/config/global_configuration $TMPDIR
cp /mnt/flash/config/global_option $TMPDIR
cp /mnt/flash/config/user_defined_notification $TMPDIR
cp /mnt/flash/config/user_factory_defaults $TMPDIR
cp /mnt/flash/config/ptp/tsu_config $TMPDIR

cp /var/log/*messages $TMPDIR
cp /var/log/initialized* $TMPDIR
cp /var/log/*.gz $TMPDIR

run_command network ! ifconfig -a
run_command network ! route 
run_command network ! ip link 
if [ -d /proc/net/bonding ]; then
   run_command bonding ! cat /proc/net/bonding/bond0
   run_command bonding ! cat /proc/net/bonding/bond1
   run_command bonding ! cat /proc/net/bonding/bond2
   run_command bonding ! cat /proc/net/bonding/bond3
fi   

run_command system ! uname -r
run_command system ! uptime
run_command system ! ps aux
run_command system ! free
run_command system ! cat /proc/meminfo

run_command dmesg ! dmesg

run_command disks ! mount
run_command disks ! df -h
run_command flash ! du -h /mnt/flash

run_command dir_listings ! ls -lR /mnt/flash
run_command dir_listings ! ls -lR /etc
run_command dir_listings ! ls -lR /var/log

# NTP Association Informations

cp /etc/ntp.conf $TMPDIR
cp /etc/ntp.drift $TMPDIR

run_command ntp ! ntpq -p
run_command ntp ! ntpq -c as

ntpq -c as | grep -v "==" | grep -v "assID" | while read a b c
do
  ntpq -c "rv $b" | run_command ntp "Readvars Association ID $b"
  ntpq -c "cv $b" | run_command ntp "Clockvars Association ID $b"
done

cp /var/log/loopstat* $TMPDIR


if [ -e /usr/bin/congainfo ]; then
  run_command board ! /usr/bin/congainfo
fi


# Pack your bags and go home

cd /tmp/diagnostics
tar -cf /www/ltdiag.tar *
gzip /www/ltdiag.tar
mv /www/ltdiag.tar.gz /www/ltdiag.tgz
cd /tmp
rm -R diagnostics

