#!/bin/bash
#
# Diagnose Script for cable modem or other internet connections
#
#    To run this script you can simply type: sh diagnose.sh
#    It will create a file diagnose.txt that can be sent to a
#    service tech for analysis.
#
#    This script requires bash shell to run as well as ifconfig, 
#    netstat, ping, traceroute and awk. It will automatically 
#    look in the usuall places for these commands. 
#
# (C) 2003 www.brayra.com
# Written by Richard A. Bray
#
# This script is licensed under the GPL (http://www.gnu.org/copyleft/gpl.html)
#

# set_cmd <VAR> <CMD>
#   this will assign with the program CMD with the correct path
set_cmd()
{
  if [ $# -lt 2 ] ; then
    echo "ERROR: invalid params sent to set_cmd." >&2
    exit 2
  fi
  if [ -f "/sbin/$2" ] ; then
    eval "$1=/sbin/$2"
  else
    if [ -f "/usr/sbin/$2" ] ; then
      eval "$1=/usr/sbin/$2"
    else
      if [ -f "/bin/$2" ] ; then
        eval "$1=/bin/$2"
      else
        if [ -f "/usr/bin/$2" ] ; then
          eval "$1=/usr/bin/$2"
        else
          echo "ERROR: command ($2) not found."
          exit 1
        fi
      fi
    fi
  fi
}
set_cmd IFCONFIG ifconfig
set_cmd NETSTAT netstat
set_cmd PING ping
set_cmd TRACEROUTE traceroute
set_cmd AWK awk
NS=`cat /etc/resolv.conf|grep -v '^ *#'|grep nameserver|$AWK '{print $2}'`

echo "Setting Variables"
#set variables
GATEWAY=`netstat -rn|grep ^0.0.0.0 |$AWK '{print $2}'`
IFACE=`netstat -rn|grep ^0.0.0.0 |$AWK '{print $8}'`
SELF=`$IFCONFIG $IFACE|grep Mask|$AWK '{print $2}'`
SELF=${SELF##*:}

checkit()
{
  echo "Checking: $1" >&2
  $PING -c 3 $1
  $TRACEROUTE $1 2>&1
}

diagnose()
{
  echo "==================================================================="
  echo "LOCAL IP"
  echo ""
  checkit $SELF
  echo ""
  echo "..................................................................."
  echo "GATEWAY"
  echo ""
  checkit $GATEWAY
  for x in $NS ; do
    echo ""
    echo "..................................................................."
    echo "NAMESERVER"
  echo ""
    checkit $x
  done
  echo ""
  echo "..................................................................."
  echo "LOOPBACK"
  echo ""
  checkit 127.0.0.1
  echo ""
  echo "..................................................................."
  echo "www.yahoo.akadns.net"
  echo ""
  checkit www.yahoo.akadns.net
  echo ""
  echo "..................................................................."
  echo "metalab.unc.edu"
  echo ""
  checkit metalab.unc.edu
  echo ""
  echo "==================================================================="
  echo "Current Network Interface Status"
  echo ""
  $IFCONFIG $IFACE
  echo ""
  echo "==================================================================="
  echo "Current transmition routes"
  echo ""
  $NETSTAT -r
  echo ""
  echo "==================================================================="
  echo "NETSTAT"
  echo ""
  $NETSTAT -ln --tcp --udp
}

echo "Running Test"
diagnose >diagnose.txt

