#!/bin/bash
#
#  Copyright (C) 2006,2010 <framp@linux-tips-and-tricks.de>
#
#  $Id: collectNWData.sh,v 1.199 2010/02/20 17:25:58 framp Exp $
#
# Summary:
#   Short script which analyzes network problems and collects network information on Linux systems.
#
# For more details and the latest version go to http://www.linux-tips-and-tricks.de/collectNWData
#
# History:
#	04/08/06 - Initial version
# 	06/07/06 - Added iptables -L -vn
# 	06/23/06 - Comments and empty lines removed from resolv.conf
# 	06/23/06 - cat /proc/sys/net/ipv4/ip_forward added
# 	07/12/06 - added -n to route and iptables -t nat -L
#	07/18/06 - added lspci, lsusb and iwconfig, pingMyLocalIPs and ping www.sue.de via name and IP
#	07/21/06 - added uname -a and query of suse version
#	07/29/06 - Introduced flags in order to control the amount of output and reduced numer of output lines
#	09/02/06 - removed bug in pingLocalIPs on German systems
#                  detail level can now be controlled with options
#		   /etc/sysconfig/network/ifcfg-* files will be included (wireless credentials are filtered)
#	09/22/06 - added masquerading of WLAN keys with test support from Rain_Maker
#	10/08/06 - added masquerading of WLAN encryption key in iwconfig with test support from Rain_Maker
#	11/03/06 V0.3.4 - added output of invocation parameters in log
#	02/03/07 V0.3.5 - added additional ouput of config files (ssh, dhcp, proxy, ...) and some usability enhancements
#	02/04/07 V0.3.6 - combined all pings and some usability enhancements
#	03/04/07 V0.4.0 - first experimental NWEliza function added, localization for German and English added
#			- check for missing or invalid default gateway
#			- check for missing or invalid DNS entry
#	03/11/07 V0.4.1 - check for existance of any nics and whether they miss an IP
#			- check whether two different nics go into the same subnet
#	04/04/07 V0.4.2 - use lspci to check whether there is a network card available on the system
#	04/06/07 V0.4.3 - use lsmod and arp to get further info
#	04/13/07 V0.4.3.1 - minor enhancements
#	04/13/07 V0.4.3.2 - minor enhancements (progress messages)
#	05/14/07 V0.4.4	- removed restriction to SuSE distri
#	05/20/07 V0.4.4.1 - some typos removed
#	05/20/07 V0.4.4.2 - mod check corrected
#	05/25/07 V0.4.4.3 - reduced number of messages and changed progress message
#	05/29/07 V0.4.4.4 - fixed bug in checkForValidNic (no result for message returned)
#	06/01/07 V0.4.5 - NWeliza now executes all tests and doesn't terminate when the first problem was found
#			  Added comments and question for execution host
#	11/05/07 V0.5 - Added error message numbers. Detailed instructions how to fix the problem can be
#				found on www.wiki.framp.de.
#			Added self test code
#	11/18/07 V0.5.0.1 - Added automatic switch to root if script is invoked by normal user
#			Added additional useful commands to get info about installed firmware (thx to Rain_Maker)
#	11/22/07 V0.5.1 - Added checks for missing firmware for WLAN cards (thx to Rain_Maker)
#	11/24/07 V0.5.1.1 - Added check for MTU
#	12/19/07 V0.5.1.2 - Added WLAN cards in check for checkForValidNic
#	01/06/08 V0.5.1.3 - MTU check done only for direct connected clients or routers, cleanup
#	01/07/08 V0.5.2 - Check for APIPA IP adresses (169.254.0.0/16) assigned to nics
#	02/04/08 V0.5.2.1 - Added pointer to nopaste phpfi.com
#	02/21/08 V0.5.2.2 - Added support for Arch Linux (thx to Rain_Maker) [messages*]
#	03/14/08 V0.5.2.3 - Added check for interface errors
#	03/14/08 V0.5.2.4 - Added check for ipv6 usage (thx to Grothesk)
#				and fixed bug in checkForNicErrors (IPV6 ignored)
#				and fixed bug in checkForNicsInSameSubnet (== instead of eq used in comparison)
#	03/28/08 V0.5.2.5 - Dropped www.wiki.framp.de now pointing to www.linux.framp.de
#	03/29/08 V0.5.2.6 - Added two additional useful greps (thx to Rain_Maker) and fixed bug with passed parameters to su
#	03/30/08 V0.5.2.7 - Corrected deletion of comment lines and detectFirmwareMessages now produces an message if nothing was found
#	04/02/08 V0.5.2.8 - Script now located on www.linux-tips-and-tricks.de
#	04/12/08 V0.5.2.9 - Corrected tr bug for modules and result file is now created in directory the script resides
#	04/14/08 V0.5.2.10 - Output file collectNWData.out will be written in the same directory the script was downloaded and will get ownership of the script invoker
#	04/18/08 V0.5.2.11 - Fixed division by zero in checkForNicErrors
#	04/19/08 V0.5.2.12 - Added -nn to lspci (thx to Grothesk)
#	04/20/08 V0.5.2.13 - Appended sort after lsmod (thx to Grothesk)
#	04/30/08 V0.5.2.14 - Minor fixes
#	05/27/08 V0.5.3 - Added additional wireless accesspoint topology thus WLAN info is now collected for WLAN topology only
#							and shortens output for wired topologies
#							and NWEliza now executes WLAN checks only for WLN topology
#							and WLAN if checks and wired if checks are now separated
#							and added NWEliza check checkKnetWorkManager in case of WLAN toplology (thx to Grothesk)
#							and output file has now extension .txt for ease of use
#							and various misc updates/minor fixes
#
#	05/29/08 V0.5.3.1 - Introduced connection type (wired/wireless) to control NWEliza
#	06/29/08 V0.6 - Refactored NWEliza into common-, wired- and wireless sections, restructure NWEliza logic and a lot of other enhancements
#       08/10/08 V0.6.1 - Added various ndiswrapper checks (thx Grothesk and rain_maker), knetworkmanager checks, dhcp error checks and NIC config checks
#       08/20/08 V0.6.1.1 - Added check for WLAN kill switch
#       08/26/08 V0.6.1.2 - Added check for ESSID
#       09/02/08 V0.6.1.3 - Added check for DHCP
#       09/06/08 V0.6.1.4 - Check for active wired connection if wireless connection should be tested and create error message
#       09/27/08 V0.6.1.5 - Public IPs and all mac addresses are masqueraded
#       09/28/08 V0.6.1.6 - Script now can be started with just one mouse click from the desktop
#       11/11/08 V0.6.1.7 - Added additional info from SuSE hwinfo command provided if hwinfo is available
#       12/04/08 V0.6.1.8 - Using dhcpcd-test to gather dhcp info
#       03/20/09 V0.6.1.9 - NWEliza uses iwlist for WLAN problem detection (thx to lwfinger)
#       05/19/09 V0.6.1.10 - Check hwinfo results for non loaded modules and inactive modules
#	   until V0.6.1.26 - Various small enhancements (See CVS checkin comments)
#       20/01/10 V0.6.2.0 - Enabled collectNWData for other Linux distros based on RedHat, Debian, Arch and Slackware
#				Tested distros are Arch, Debian, Knoppix, Kubuntu, Mint, Mandriva, CentOS, Fedora and Slackware
#				Thx Rain_Maker, Grothesk and Glako for their beta tests
#	02/14/10 V0.6.3.0 - Script now can be called as normal user but with reduced analysis functionality
#
# For more details and the latest version go to http://www.linux-tips-and-tricks.de/collectNWData

function queryDistro () {

local distro
local detectedDistro="Unknown"
local regExpLsbFile="/etc/(.*)[-_]"

# Returned distro       Distribution the script was tested on
# ---------------------------------------------------------
# suse                  openSuSE 11.0 (no lsb_release) and 11.2 (lsb_release)
# redhat                Fedora 12
# redhat                CentOS 5.4
# debian                Kubuntu 9.10
# debian                Debian 5.0.3
# arch                  Arch
# slackware             Slackware 13.0.0.0.0
# redhat                Mandriva 2009.1
# debian                Knoppix 6.2
# debian                Mint 8

UNKNOWN_DISTRO=-1
SUSE=0
REDHAT=1
DEBIAN=2
ARCH=3
SLACKWARE=4

etcFiles=`ls /etc/*[-_]{release,version} 2>/dev/null`
for file in $etcFiles; do
   if [[ $file =~ $regExpLsbFile ]]; then
      nextDetectedDistro=${BASH_REMATCH[1]}
      if [[ $nextDetectedDistro == "lsb" ]]; then
         continue
      fi
      detectedDistro=$nextDetectedDistro
      if [[ $nextDetectedDistro == "redhat" ]]; then
         break
      fi

   else
      echo "??? Should not occur: Don't find any etcFiles ???"
      exit 1
   fi
done

DISTRO_NAME=$detectedDistro

distro=`echo $detectedDistro | tr "[:lower:]" "[:upper:]"`
DISTRO="DISTRO=\$$distro"
eval $DISTRO

}

#################################################################################
#################################################################################
#################################################################################
#
# --- various constants
#
#################################################################################
#################################################################################
#################################################################################

CVS_VERSION="V0.6.3.0"
CVS_REVISION="$Revision: 1.199 $"
CVS_DATE="$Date: 2010/02/20 17:25:58 $"
CVS_DATE_ONLY=${CVS_DATE/: /}
CVS_DATE_ONLY=${CVS_DATE_ONLY/ \$/}
CVS_REVISION_ONLY=${CVS_REVISION/: /}
CVS_REVISION_ONLY=${CVS_REVISION_ONLY/ \$}

queryDistro

VERSION="$CVS_VERSION (Rev: ${CVS_REVISION_ONLY}, Build: ${CVS_DATE_ONLY} UTC)"
BASEURL="www.linux-tips-and-tricks.de"
AUTHOR="framp"
CONTACT="framp@linux-tips-and-tricks.de"
HTTP_ROOT_ACCESS="http://$BASEURL/CND_rootAccess"
HTTP_UPLOAD_URL="http://$BASEURL/CND_UPL"
HTTP_HELP_URL="http://$BASEURL/CND"

case $LANG in
      de_*)
         ;;
      *)
         HTTP_HELP_URL="${HTTP_HELP_URL}#English"
         HTTP_ROOT_ACCESS="${HTTP_ROOT_ACCESS}#English"
         HTTP_UPLOAD_URL="${HTTP_UPLOAD_URL}#English"
      ;;
   esac;

COPYRIGHT="Copyright (C) 2006,2010 by ${AUTHOR}"
MYSELF="${0##*/}"
CODE_BEGIN="[code]"
CODE_END="[/code]"
DEBUG="off"

SEPARATOR="=================================================================================================================="
MINOR_SEPARATOR="------------------------------------------------------------------------------------------------------------------"
VERSION_STRING="$MYSELF $VERSION"
LOG="/tmp/${MYSELF}$$"
HELP_WIKI="http://www.linux-tips-and-tricks.de"
NUMBER_OF_LINES_TO_CHECK_IN_VAR_LOG_MESSAGES=300
MAX_ERROR_PERCENT=30                   # acceptable error rate on interfaces (xmit and rcv)

# --- get the absolute path of script such that the output file can be written in the same directory

PRG_DIR=`dirname $0`
OLD_PWD=`pwd`
cd $PRG_DIR
export CND_DIR=`pwd`
cd $OLD_PWD

if [[ $UID -eq 0 || $USE_ROOT != "1" ]]; then
   FINAL_RESULT="${CND_DIR}/${MYSELF/.sh/}.txt"
   FINAL_RESULT_SHORT_NAME="${MYSELF/.sh/}.txt"
   STATE="/tmp/${MYSELF}_S.$$"
   ELIZA_RESULT="/tmp/${MYSELF}_E.$$"
   CND_USER=$USER
else
   export CND_USER=$USER               # for chown at the end of script
fi

#################################################################################
# --- tools needed by the script
#
# LSUSB checked at runtime - not beforehand - because it's not installed all the time
#################################################################################

MODS_SUSE="EGREP AWK SED IFCONFIG IWCONFIG IWLIST IPTABLES LSPCI GREP PERL ARP ROUTE LSMOD SORT PING TAIL HWINFO DHCPCD"
MODS_OTHER="EGREP AWK SED IFCONFIG IWCONFIG IWLIST IPTABLES LSPCI GREP PERL ARP ROUTE LSMOD SORT PING TAIL"

#################################################################################
# Make sure script runs in a console
#################################################################################

tty -s;
if [ $? -ne 0 ]; then
#  konsole --noclose -T "collectNWData.sh" --vt_sz 132x25 -e "$0";
  konsole -e "$0"
  exit;
fi

#################################################################################
# --- cleanup files in case of failure
#################################################################################

function cleanupTempFiles {
	rm -f $LOG 2>/dev/null
	rm -f $ELIZA_RESULT 2>/dev/null
	rm -f $STATE 2>/dev/null
}

function cleanupFiles {
	rm -f $FINAL_RESULT 2>/dev/null
	cleanupTempFiles
	exit
}

trap 'cleanupFiles' SIGHUP SIGINT SIGPIPE SIGTERM

#################################################################################
#
# --- Messages in English and German
#
# (volunteers to translate the messages into other languages are welcome)
#
#################################################################################

MSG_UNDEFINED=0
MSG_E[$MSG_UNDEFIND]="Undefined message. Pls inform the author $CONTACT"
MSG_G[$MSG_UNDEFINED]="Unbekannte Meldung. Bitte den Author $CONTACT informieren"
MSG_ELIZA_WELCOME=1
MSG_E[$MSG_INTERNAL_ERROR]="Internal error %1 occured. Pls inform the author $CONTACT"
MSG_G[$MSG_INTERNAL_ERROR]="Interner Fehler %1 aufgetreten. Bitte den Author $CONTACT informieren"
MSG_ELIZA_START_ANALYZE=2
MSG_E[$MSG_ELIZA_START_ANALYZE]="--- NWEliza is analyzing the system for common network configuration errors ..."
MSG_G[$MSG_ELIZA_START_ANALYZE]="--- NWEliza untersucht das System nach haeufigen Netzwerkkonfigurationsfehlern untersucht ..."
MSG_START_COLLECTING=3
MSG_E[$MSG_START_COLLECTING]="--- NWCollect is collecting networkconfiguration information into file %1 ..."
MSG_G[$MSG_START_COLLECTING]="--- NWCollect sammelt Netzwerkkonfigurationsinformationen in Datei %1 ..."
MSG_CON_WRL=4
MSG_E[$MSG_CON_WRL]="--- (2) Wireless connection (WLAN)"
MSG_G[$MSG_CON_WRL]="--- (2) Kabellose Verbindung (WLAN)"
MSG_EMPTY_LINE=5
MSG_E[$MSG_EMPTY_LINE]=""
MSG_G[$MSG_EMPTY_LINE]=""
MSG_MAIN_SUSE_ONLY=6
MSG_E[$MSG_MAIN_SUSE_ONLY]="!!! Script tested on SuSE systems only. Data collection and analysis steps may fail and is ignored!"
MSG_G[$MSG_MAIN_SUSE_ONLY]="!!! Das Script wurde nur auf SuSE Installationen getestet. Datensammlungs- und Analyseschritte können abbrechen und werden uebersprungen!"
MSG_MAIN_PROG_REQUIRED=7
MSG_E[$MSG_MAIN_PROG_REQUIRED]="!!! Program %1 not found. Install program and invoke script again"
MSG_G[$MSG_MAIN_PROG_REQUIRED]="!!! Das Programm %1 ist nicht verfuegbar. Das Programm nachinstallieren und das Script danach noch einmal ausfuehren"
MSG_MAIN_NO_ERROR_DETECTED=8
MSG_E[$MSG_MAIN_NO_ERROR_DETECTED]="--- No obvious errors/warnings detected. Post contents of file %1 in your favorite Linux forum and read $HTTP_UPLOAD_URL"
MSG_G[$MSG_MAIN_NO_ERROR_DETECTED]="--- Keine offensichtlichen Konfigurationsfehler/-warnungen gefunden. Die Datei %1 im bevorzugten Linux Forum posten und $HTTP_UPLOAD_URL lesen."
#MSG_KEY_WARNING=9
#MSG_E[$MSG_KEY_WARNING]="--- %1 errors detected"
#MSG_G[$MSG_KEY_WARNING]="--- %1 Fehler gefunden"
MSG_MAIN_VERSION=10
MSG_E[$MSG_MAIN_VERSION]="%1 %2 %3 %4 %5 %6 %7 %8 %9 %10"
MSG_G[$MSG_MAIN_VERSION]="%1 %2 %3 %4 %5 %6 %7 %8 %9 %10"
MSG_GET_TOPLOLOGY=11
MSG_E[$MSG_GET_TOPOLOGY]="--- What's the type of networktopology?"
MSG_G[$MSG_GET_TOPOLOGY]="--- Welche Netzwerktopologie liegt vor?"
MSG_UNSUPPORTED_TOPOLOGY=12
MSG_E[$MSG_UNSUPPORTED_TOPOLOGY]="--- Unknown topology"
MSG_G[$MSG_UNSUPPORTED_TOPOLOGY]="--- Netzwerktopology unbekannt"
MSG_STRING=13
MSG_E[$MSG_STRING]="%1."
MSG_G[$MSG_STRING]="%1."
MSG_PLEASE_CORRECT_ANSWER=14
MSG_E[$MSG_PLEASE_CORRECT_ANSWER]="--- Please answer with 1-%1: "
MSG_G[$MSG_PLEASE_CORRECT_ANSWER]="--- Bitte mit 1-%1 anworten: "
MSG_TOPO_DM_LC=15
MSG_E[$MSG_TOPO_DM_LC]="--- (1) DSL modem <---> LinuxClient"
MSG_G[$MSG_TOPO_DM_LC]="--- (1) DSL modem <---> LinuxClient"
MSG_TOPO_DR_LC=16
MSG_E[$MSG_TOPO_DR_LC]="--- (2) DSL HW router <---> LinuxClient"
MSG_G[$MSG_TOPO_DR_LC]="--- (2) DSL HW router <---> LinuxClient"
MSG_TOPO_DM_LR_LC=17
MSG_E[$MSG_TOPO_DM_LR_LC]="--- (3) DSL modem  <---> LinuxRouter <---> LinuxClient"
MSG_G[$MSG_TOPO_DM_LR_LC]="--- (3) DSL modem  <---> LinuxRouter <---> LinuxClient"
MSG_TOPO_DR_LR_LC=18
MSG_E[$MSG_TOPO_DR_LR_LC]="--- (4) DSL HW router <---> LinuxRouter <---> LinuxClient"
MSG_G[$MSG_TOPO_DR_LR_LC]="--- (4) DSL HW router <---> LinuxRouter <---> LinuxClient"
MSG_MAIN_POST_FILE=27
MSG_E[$MSG_MAIN_POST_FILE]="--- Place  the contents of file %1 in the net (see $HTTP_UPLOAD_URL for links) \n--- and then paste the nopaste link on your favorite Linux forum. "
MSG_D[$MSG_MAIN_POST_FILE]="--- Den Inhalt der Datei %1 im Netz ablegen (Links siehe $HTTP_UPLOAD_URL) \n--- und dann der nopaste Link im bevorzugten Linux Forum posten."
MSG_GET_HOST=29
MSG_E[$MSG_GET_HOST]="--- On which host is the script executed?"
MSG_G[$MSG_GET_HOST]="--- Auf welchem Rechner wird das Script ausgefuehrt?"
MSG_UNSUPPORTED_HOST=30
MSG_E[$MSG_UNSUPPORTED_HOST]="--- Invalid host"
MSG_G[$MSG_UNSUPPORTED_HOST]="--- Ungültiger Rechner"
MSG_HOST_RT=31
MSG_E[$MSG_HOST_RT]="--- (2) LinuxRouter"
MSG_G[$MSG_HOST_RT]="--- (2) LinuxRouter"
MSG_HOST_CL=32
MSG_E[$MSG_HOST_CL]="--- (1) LinuxClient"
MSG_G[$MSG_HOST_CL]="--- (1) LinuxClient"
MSG_MAIN_BECOME_ROOT=33
MSG_E[$MSG_MAIN_BECOME_ROOT]="--- Please enter the root password."
MSG_G[$MSG_MAIN_BECOME_ROOT]="--- Bitte das root Kennwort eingeben."
MSG_CON_WRD=40
MSG_E[$MSG_CON_WRD]="--- (1) Wired connection"
MSG_G[$MSG_CON_WRD]="--- (1) Kabelgebundene Verbindung"
MSG_GET_CONNECTION=41
MSG_E[$MSG_GET_CONNECTION]="--- Which type of your network connection should be tested?"
MSG_G[$MSG_GET_CONNECTION]="--- Welcher Netzwerkverbindungtyp soll getestet werden?"
MSG_UNSUPPORTED_CONNECTION=42
MSG_E[$MSG_UNSUPPORTED_CONNECTION]="--- Unknown network connection type"
MSG_G[$MSG_UNSUPPORTED_CONNECTION]="--- Netzwerkverbindungstyp unbekannt"
MSG_MAIN_WARNING_DETECTED=43
#MSG_E[$MSG_MAIN_WARNING_DETECTED]="--- %1 warnings detected"
#MSG_G[$MSG_MAIN_WARNING_DETECTED]="--- %1 Warnungen gefunden"
MSG_MAIN_GOTO_LINK=44
MSG_E[$MSG_MAIN_GOTO_LINK]="--- Go to $HTTP_HELP_URL to get more detailed instructions \n--- about the error/warning messages and how to fix the problems on your own"
MSG_G[$MSG_MAIN_GOTO_LINK]="--- Gehe zu $HTTP_HELP_URL um detailiertere Hinweise \n--- zu den Fehlermeldungen/Warnungen zu bekommen und wie die Fehler selbst beseitigt werden koennen"
MSG_TOPO_AP_LC=46
MSG_E[$MSG_TOPO_AP_LC]="--- (1) WLAN access point <---> LinuxClient"
MSG_G[$MSG_TOPO_AP_LC]="--- (1) WLAN access point <---> LinuxClient"
MSG_TOPO_WR_LC=47
MSG_E[$MSG_TOPO_WR_LC]="--- (2) WLAN HW router <---> LinuxClient"
MSG_G[$MSG_TOPO_WR_LC]="--- (2) WLAN HW router <---> LinuxClient"
MSG_TOPO_AP_LR_LC=48
MSG_E[$MSG_TOPO_AP_LR_LC]="--- (3) WLAN access point <---> LinuxRouter <---> LinuxClient"
MSG_G[$MSG_TOPO_AP_LR_LC]="--- (3) WLAN access point <---> LinuxRouter <---> LinuxClient"
MSG_TOPO_WR_LR_LC=49
MSG_E[$MSG_TOPO_WR_LR_LC]="--- (4) WLAN HW router <---> LinuxRouter <---> LinuxClient"
MSG_G[$MSG_TOPO_WR_LR_LC]="--- (4) WLAN HW router <---> LinuxRouter <---> LinuxClient"
MSG_ASK_FOR_ROOT=59
MSG_E[$MSG_ASK_FOR_ROOT]="--- Invoking this script as root allows a more detailed analysis and will give better results. \n--- If you have any concerns to execute the script as root please read $HTTP_ROOT_ACCESS.\n--- Do you want to run the scrip as root (y/n)?"
MSG_G[$MSG_ASK_FOR_ROOT]="--- Der Aufruf des Scripts als root erleubt eine detailiertere Analyse und liefert bessere Ergebnisse. \n--- Falls Bedenken existieren das Script als root auszufuehren bitte $HTTP_ROOT_ACCESS lesen.\n--- Willst Du das Script als root ausführen lassen (j/n)?"
#MSG_NO_ANALYSIS_AS_USER=62
#MSG_E[$MSG_NO_ANALYSIS_AS_USER]="!!! CND0460I: Analysis of %1 only possible if script is invoked as root"
#MSG_G[$MSG_NO_ANALYSIS_AS_USER]="!!! CND0460I: Analyse von %1 nur moeglich wenn das Script als root aufegrufen wird"
#MSG_MASQ_IP=63
#MSG_E[$MSG_MASQ_IP]="--- Masqueraded %1 IP addresses"
#MSG_G[$MSG_MASQ_IP]="--- %1 Ã¶ffentliche IPs maskiert"
#MSG_MASQ_MAC=64
#MSG_E[$MSG_MASQ_MAC]="--- Masqueraded %1 MAC addresses"
#MSG_G[$MSG_MASQ_MAC]="--- %1 MAC Addressen maskiert"
#MSG_MASQ_ESSID=65
#MSG_E[$MSG_MASQ_ESSID]="--- Masqueraded %1 ESSIDs"
#MSG_G[$MSG_MASQ_ESSID]="--- %1 ESSIDs maskiert"
#
#
#
MSG_NO_NIC_FOUND=300
MSG_E[$MSG_NO_NIC_FOUND]="!!! CND0100E: No network card for the selected connection type was found on the system"
MSG_D[$MSG_NO_NIC_FOUND]="!!! CND0100E: Keine Netzwerkkarte für den gewählten Verbindungstyp kann auf dem System gefunden werden"
MSG_NO_VALID_NI_FOUND=301
MSG_E[$MSG_NO_VALID_NI_FOUND]="!!! CND0110E: For the selected connection type there was no active network interface found on your system"
MSG_D[$MSG_NO_VALID_NI_FOUND]="!!! CND0110E: Es wurde keine aktives Netzwerkinterface auf dem System für der gewaehlten Verbindungstyp gefunden"
MSG_NO_IP_ASSIGNED_TO_NIC=302
MSG_E[$MSG_NO_IP_ASSIGNED_TO_NIC]="!!! CND0120E: Network card %1 has no IP address"
MSG_D[$MSG_NO_IP_ASSIGNED_TO_NIC]="!!! CND0120E: Die Netzwerkkarte %1 hat keine IP Adresse"
MSG_DUPLICATE_NETWORKS=303
MSG_E[$MSG_DUPLICATE_NETWORKS]="!!! CND0130E: There is more than one network card defined in the same subnet: %1"
MSG_D[$MSG_DUPLICATE_NETWORKS]="!!! CND0130E: Es ist mehr als eine Netzwerkkarte im selben Subnetz definiert: %1"
MSG_NO_DEFAULT_GATEWAY_SET=304
MSG_E[$MSG_NO_DEFAULT_GATEWAY_SET]="!!! CND0140E: No default gateway set on your system"
MSG_G[$MSG_NO_DEFAULT_GATEWAY_SET]="!!! CND0140E: Kein default gateway auf dem System definiert"
MSG_CHECK_DEFAULT_GATEWAY_SETTING=305
MSG_E[$MSG_CHECK_DEFAULT_GATEWAY_SETTING]="!!! CND0150E: There might be problems with the default gateway definition %1 on interface %2"
MSG_G[$MSG_CHECK_DEFAULT_GATEWAY_SETTING]="!!! CND0150E: Es kann ein Problem mit der default gateway definition %1 am Interface %2 vorliegen"
MSG_NAMESERVER_NOT_ACCESSIBLE=306
MSG_E[$MSG_NAMESERVER_NOT_ACCESSIBLE]="!!! CND0160E: Unable to access nameserver with IP %1 defined in /etc/resolv.conf"
MSG_G[$MSG_NAMESERVER_NOT_ACCESSIBLE]="!!! CND0160E: Auf den definierter Nameserver mit der IP %1 in /etc/resolv.conf kann nicht zugegriffen werden"
MSG_NO_NAMESERVER_DEFINED=307
MSG_E[$MSG_NO_NAMESERVER_DEFINED]="!!! CND0170E: No nameserver defined in /etc/resolv.conf"
MSG_G[$MSG_NO_NAMESERVER_DEFINED]="!!! CND0170E: Kein Nameserver in /etc/resolv.conf definiert"
MSG_CANT_PING_EXTERNAL_IP=308
MSG_E[$MSG_CANT_PING_EXTERNAL_IP]="!!! CND0180I: The system can't ping external IP address %1"
MSG_G[$MSG_CANT_PING_EXTERNAL_IP]="!!! CND0180I: Das System kann die externe IP %1 nicht pingen"
MSG_POSSIBLE_WLAN_FIRMWARE_PROBLEMS=309
MSG_E[$MSG_POSSIBLE_WLAN_FIRMWARE_PROBLEMS]="!!! CND0190E: WLAN firmware is missing or cannot be loaded"
MSG_G[$MSG_POSSIBLE_WLAN_FIRMWARE_PROBLEMS]="!!! CND0190E: WLAN Firmware fehlt oder kann nicht geladen werden"
MSG_POSSIBLE_MTU_PROBLEMS=310
MSG_E[$MSG_POSSIBLE_MTU_PROBLEMS]="!!! CND0200W: Maximum possible MTU is %1, but actual MTU on nic %2 is %3"
MSG_G[$MSG_POSSIBLE_MTU_PROBLEMS]="!!! CND0200W: Die maximal ermittelte MTU ist %1, aber die aktuelle MTU an der Netzwerkkarte %2 ist %3"
MSG_APIPA_DETECTED=311
MSG_E[$MSG_APIPA_DETECTED]="!!! CND0210W: APIPA IP address %1 detected on network card %2"
MSG_G[$MSG_APIPA_DETECTED]="!!! CND0210W: APIPA IP Adresse %1 wurde an Netzwerkkarte %2 entdeckt"
MSG_NIC_ERRORS=312
MSG_E[$MSG_NIC_ERRORS]="!!! CND0220W: Serious transmissionerrors on network interface %1 detected"
MSG_G[$MSG_NIC_ERRORS]="!!! CND0220W: Ungewoehnlich viele Uebertragungsfehler am Interface %1 entdeckt"
MSG_IPV6_DETECTED=313
MSG_E[$MSG_IPV6_DETECTED]="!!! CND0230W: IPV6 enabled"
MSG_G[$MSG_IPV6_DETECTED]="!!! CND0230W: IPV6 ist eingeschaltet"
MSG_KNETWORKMANAGER_ERROR=314
MSG_E[$MSG_KNETWORKMANAGER_ERROR]="!!! CND0240E: knetworkmanager for network configuration enabled but a YAST network card configuration for %1 exist"
MSG_G[$MSG_KNETWORKMANAGER_ERROR]="!!! CND0240E: Knetworkmanager wird fuer die Netzwerkkonfiguration benutzt aber eine YAST Netzwerkkartenkonfiguration für %1 existiert"
MSG_CANT_LOOKUP_EXTERNAL_DNS=315
MSG_E[$MSG_CANT_LOOKUP_EXTERNAL_DNS]="!!! CND0250E: The system can't lookup external DNS name %1"
MSG_G[$MSG_CANT_LOOKUP_EXTERNAL_DNS]="!!! CND0250E: Das System kann den externen Namen %1 nicht aufloesen"
MSG_NDISWRAPPER_PROB=316
MSG_E[$MSG_NDISWRAPPER_PROB]="!!! CND0260E: ndiswrapper for %1 can't be used in parallel with linux native driver %2"
MSG_G[$MSG_NDISWRAPPER_PROB]="!!! CND0260E: ndiswrapper für %1 kann nicht gemeinsam mit dem linux Treiber %2 benutzt werden"
MSG_NDISWRAPPER_FW_PROB=317
MSG_E[$MSG_NDISWRAPPER_FW_PROB]="!!! CND0270E: Used windows driver %1 was either not installed completely (e.g. sys files are missing) or is from a wrong windows version (e.g. Win 98 instead of XP)"
MSG_G[$MSG_NDISWRAPPER_FW_PROB]="!!! CND0270E: Der verwendete Windowstreiber %1 wurde entweder nicht vollständig installiert (Treiberbestandteile fehlen z.B. sys Dateien) oder ist von der falschen Windows-Version (z.B. Win 98 statt XP)"
MSG_NDISWRAPPER_ARCH_PROB=318
MSG_E[$MSG_NDISWRAPPER_ARCH_PROB]="!!! CND0280E: Inkompatible windows driver architecture of %1 and Linux architecture (32 bit and 64 bit architecture mixed)"
MSG_G[$MSG_NDISWRAPPER_ARCH_PROB]="!!! CND0280E: Inkompatible Windowstreiber Architektur von %1 und Linux Architektur (32 Bit und 64 Bit Architektur gemischt)"
MSG_NO_NIC_CONFIG_FOUND=319
MSG_E[$MSG_NO_NIC_CONFIG_FOUND]="!!! CND0290E: No network configuration found for interface %1"
MSG_G[$MSG_NO_NIC_CONFIG_FOUND]="!!! CND0290E: Keine Netzwerkkonfiguration für Interface %1 gefunden"
MSG_NO_DHCP_FOUND=320
MSG_E[$MSG_NO_DHCP_FOUND]="!!! CND0300E: No dhcp server found on interface %1"
MSG_G[$MSG_NO_DHCP_FOUND]="!!! CND0300E: Keinen dhcp Server am Interface %1 gefunden"
MSG_IFUP_CONFIGURED=321
MSG_E[$MSG_IFUP_CONFIGURED]="!!! CND0310W: Classic network configuration with ifup was detected. Configuration with knetworkmanager is much easier"
MSG_G[$MSG_IFUP_CONFIGURED]="!!! CND0310W: Klassische Netzwerkkonfiguration mit ifup wurde entdeckt. Die Konfiguration mit knetworkmanager ist wesentlich einfacher"
MSG_WLAN_KILL_SWITCH_ON=322
MSG_E[$MSG_WLAN_KILL_SWITCH_ON]="!!! CND0320E: WLAN turned off by hardware or software switch"
MSG_G[$MSG_WLAN_KILL_SWITCH_ON]="!!! CND0320E: WLAN ist mit dem Hardware oder Software Switch ausgeschaltet"
MSG_WLAN_AUTH_PROBS=323
MSG_E[$MSG_WLAN_AUTH_PROBS]="!!! CND0330E: WLAN credential problems exist on interface %1"
MSG_G[$MSG_WLAN_AUTH_PROBS]="!!! CND0330E: Es existierern Schluesselprobleme am Interface %1"
MSG_NO_DHCP_DETECTED=324
MSG_E[$MSG_NO_DHCP_DETECTED]="!!! CND0350W: dhcp server may not available on interface %1"
MSG_G[$MSG_NO_DHCP_DETECTED]="!!! CND0350W: Ein dhcp Server scheint nicht am Interface %1 zu existieren"
MSG_WLAN_WIRED_ONLINE=325
MSG_E[$MSG_WLAN_WIRED_ONLINE]="!!! CND0360E: Wireless connection tested with an existing wired connection on interface %1. Unplug the cable and execute the script again"
MSG_G[$MSG_WLAN_WIRED_ONLINE]="!!! CND0360E: Eine drahtlose Verbindung wurde getestet obwohl eine kabelgebundene Verbindung am Interface %1 existiert . Das Netzwerkkabel ausstecken und das Script noch einmal starten"
MSG_CANT_PING_EXTERNAL_DNS=326
MSG_E[$MSG_CANT_PING_EXTERNAL_DNS]="!!! CND0370I: The system can't ping external DNS name %1"
MSG_G[$MSG_CANT_PING_EXTERNAL_DNS]="!!! CND0370I: Das System kann den externen DNS Namen %1 nicht pingen"
MSG_WLAN_NO_SCAN=327
MSG_E[$MSG_WLAN_NO_SCAN]="!!! CND0380E: No WLANs detected on interface %1. Hardware and/or driver not configured properly"
MSG_G[$MSG_WLAN_NO_SCAN]="!!! CND0380E: Es wurden keine WLANs am Interface %1 gefunden. Die Hardware und/oder Treiber ist nicht richtig konfiguriert"
MSG_HW_NO_ACTIVE=328
MSG_E[$MSG_HW_NO_ACTIVE]="!!! CND0390E: No loaded module detected for interface %1"
MSG_G[$MSG_HW_NO_ACTIVE]="!!! CND0390E: Kein Module am Interface %1 geladen"
MSG_HW_SOME_INACTIVE=329
MSG_E[$MSG_HW_SOME_INACTIVE]="!!! CND0400W: Alternate modules %1 detected for interface %2"
MSG_G[$MSG_HW_SOME_INACTIVE]="!!! CND0400W: Es existieren weitere moegliche Module %1 für Interface %2"
MSG_NAMESERVER_NOT_VALID=330
MSG_E[$MSG_NAMESERVER_NOT_VALID]="!!! CND0410E: Configured nameserver with IP %1 is no nameserver"
MSG_G[$MSG_NAMESERVER_NOT_VALID]="!!! CND0410E: Der konfigurierte Nameserver mit der IP %1 ist kein Nameserver"
MSG_NAMESERVER_PROBLEM_UNKNOWN=331
MSG_E[$MSG_NAMESERVER_PROBLEM_UNKNOWN]="!!! CND0420E: There exists a problem with configured nameserver with IP %1"
MSG_G[$MSG_NAMESERVER_PROBLEM_UNKNOWN]="!!! CND0420E: Es gibt ein Problem mit dem konfigurierten Nameserver mit der IP %1"
MSG_NWELIZA_UNAVAILABLE=332
MSG_E[$MSG_NWELIZA_UNAVAILABLE]="!!! CND0430I: NWEliza doesn't support this Linux distribution"
MSG_G[$MSG_NWELIZA_UNAVAILABLE]="!!! CND0430I: NWEliza unterstützt diese Linux distribution nicht"
MSG_DISTRO_NOT_SUPPORTED=333
MSG_E[$MSG_DISTRO_NOT_SUPPORTED]="!!! CND0440E: This distribution is not supported"
MSG_G[$MSG_DISTRO_NOT_SUPPORTED]="!!! CND0440E: Diese Distribution wird leider nicht unterstützt"
MSG_CHECK_KEYS=334
MSG_E[$MSG_CHECK_KEYS]="!!! CND0450W: WLAN key masquerading is not fully tested on this distribution. Please check output file %1 for visible WLAN keys and masquerade them manually"
MSG_G[$MSG_CHECK_KEYS]="!!! CND0450W: WLAN Schluesselmaskierung ist nicht vollstaendig auf dieser Distribution getestet. Bitte das Ausgabefile %1 nach sichtbaren WLAN Schluesseln absuchen und manuell maskieren"
MSG_NO_ANALYSIS_AS_USER=335
MSG_E[$MSG_NO_ANALYSIS_AS_USER]="!!! CND0460I: Analysis of %1 only possible if script is invoked as root"
MSG_G[$MSG_NO_ANALYSIS_AS_USER]="!!! CND0460I: Analyse von %1 nur moeglich wenn das Script als root aufegrufen wird"
MSG_ANALYSIS_AS_USER=336
MSG_E[$MSG_ANALYSIS_AS_USER]="!!! CND0470I: Reduced analysis capability and less network information because script was not invoked as root"
MSG_G[$MSG_ANALYSIS_AS_USER]="!!! CND0470I: Reduzierte Analysefähigkeit und weniger Netzwerkinformationen da das Script nicht als root ausgeführt wurde"

#################################################################################
# Debug helper
#################################################################################

function debug() { # message
	if [[ $DEBUG == "on" ]];  then
		echo "@@@ $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10}"
	fi
}

function state() { # message
      echo "${1}${2}${3}${4}${5}${6}${7}${8}${9}${10}" >> $STATE
}

#################################################################################
# message & console handling
#################################################################################

# --- Writes a message to the console without an NL

function writeToConsoleNoNL() {	# messagenumber
	local msg
	msg=`getMessage $*`
   	echo -ne $msg >> /dev/tty
}

# --- Writes a message to the console

function writeToConsole() {	# messagenumber
	local msg
	msg=`getMessage $*`
   	echo -e $msg >> /dev/tty
}

# --- Creates a progress bar on the console

function processingMessage() { #number #maxnumber #activity
	local i
	local m
	local p
	local ip
	local mx

	m=$1

	echo -ne "\r                                               \r" >> /dev/tty
	if [[ $m != 0 ]]; then
		let ip=$m
		let p=$m*100/$2
		echo -n "($p%) "
#		for ((i=0;$i<=$m;i++)); do
#			echo -ne "."
#		done
# 	        echo -e " - Executing \" $3 \""
	fi
}

# ---Writes a messages to the NWEliza log and console

function writeToEliza() {	# messagenumber
local severity

	local msg
	msg=`getMessage $*`
  	echo -e $msg >> $ELIZA_RESULT
  	echo -e $msg >> /dev/tty

	severity=`echo $msg | cut -d " " -f 2`

	if [[ `echo $severity | $EGREP "CND[0-9]+E"` ]]; then
		let askEliza_error=$askEliza_error+1
	fi

	if [[ `echo $severity | $EGREP "CND[0-9]+W"` ]]; then
		let askEliza_warning=$askEliza_warning+1
	fi
}

# ---Writes a messages to the NWEliza log

function writeToElizaOnly() {                   	        # messagenumber
	local msg
	msg=`getMessage $*`
   	echo -e $msg >> $ELIZA_RESULT
}

# --- Helper function to extract the message text in German or English and insert message parameters

function getMessage() {			# messagenumber parm1 parm2 ...
	local msg
	local p
	local i
	local s

	case $LANG in
		de_*)
			msg=${MSG_G[$1]};		        # german
			;;
		*)
			msg=${MSG_E[$1]};       		# english
		;;
	esac;

	for (( i=2; $i <= $#; i++ )); do	        	# substitute all message parameters
		p="${!i}"
		let s=$i-1
		s="%$s"
#		msg=`$AWK -v msg="$msg" -v s=$s -v p=$p "BEGIN { sub(s,p,msg); print msg } "`
		msg=`echo $msg | $SED 's!'$s'!'$p'!'`
	done
	msg=`echo $msg | perl -p -e "s/%[0-9]+//g"`		# delete trailing %n definitions
	echo $msg
}

#################################################################################
# --- Check whether pings are possible
#
# --- Ping www.suse.de with it's IP address
# --- return 1 if ip ping failed
# --- return 0 otherwise
#
#################################################################################

function checkIPPings() {

 	debug ">>checkIPPings"

	local I
	local PING_RES
	local C
	local rc=0

   MY_IPS="195.135.220.3" 	                	# www.suse.de

   for I in $MY_IPS; do
		C=`$PING -c 3 -W 3 $I 2>&1`
		PING_RES=`echo $C | grep " 0%"`
		pingRC=$?

		if [[ $pingRC != 0 ]]; then
	   	writeToEliza $MSG_CANT_PING_EXTERNAL_IP $I
	    	let rc=1
		fi
	done

  state "PNG:$rc"
  debug "<<checkIPPings $rc"

return $rc
}

#################################################################################
# --- Execute ping tests
#
# --- Ping www.suse.de with it's IP address and dns name
#################################################################################

function pingTests() {
        local I
        local PING_RES
        local C

        MY_IPS="195.135.220.3 www.suse.de"

        for I in $MY_IPS; do
	        C="ping -c 3 -W 3 $I"
           PING_RES=`$C | grep " 0%"`

           if [[ -z $PING_RES ]]; then
              echo "Ping of $I failed"
           else
              echo "Ping of $I OK"
           fi
		done
return
}

#################################################################################
# --- Execute dhcp tests
#
# --- execute dhcpcd-test against interfaces
#################################################################################

function dhcpTests() {
local i
local C
local R

  if [[ $DISTRO == $SUSE && $USE_ROOT != "0" ]]; then

   if [[ -z $1 ]]; then

   	i=1
	while [[ $i -le $INTERFACE_NO ]]; do
	   if [[ $CONNECTION == $CONNECTION_WRL && ${INTERFACE_TYPE[$i]} == $CONNECTION_WRL ]] ||
          	  [[ $CONNECTION == $CONNECTION_WRD && ${INTERFACE_TYPE[$i]} == $CONNECTION_WRD ]]; then
# 	        C=`$DHCPCD_TEST -t 3 ${INTERFACE_NAME[$i]} 2>/dev/null`
 	        C=`$DHCPCD -Td -t 3 -NYRG -c /bin/true eth0 ${INTERFACE_NAME[$i]} 2>/dev/null`
	        R=`echo $C | grep 'offered'`
	        if [[ $? == 0 ]]; then
	          echo "${INTERFACE_NAME[$i]}: DHCP server available"
	        else
	          echo "${INTERFACE_NAME[$i]}: No DHCP server detected $C"
	        fi
	   fi
	 let i=i+1
	 done
   else
	echo "dhcpcd-test"
   fi

fi

return
}

#################################################################################
# check whether dhcp is configured either with a config file or by using knetworkmanager if there is no IP address
#
# return 0 if no dhcp was configured
# return 1 if dhcp was configured for wired connection
# return 2 if dhcp was configured for wireless connection
#################################################################################

function checkDHCP() {
local rc=0
local conf=0
local C
local R

   debug ">>checkDHCP"

   C=`$EGREP -i 'NETWORKMANAGER.*=.*yes' /etc/sysconfig/network/config `
   knme=$?

   i=1
   while [[ $i -le $INTERFACE_NO ]]; do
      if [[ $CONNECTION == $CONNECTION_WRL && ${INTERFACE_TYPE[$i]} == $CONNECTION_WRL ]] ||
            [[ $CONNECTION == $CONNECTION_WRD && ${INTERFACE_TYPE[$i]} == $CONNECTION_WRD ]]; then

         if [[ ${INTERFACE_IP[$i]} == "" ]]; then                                           # no IP address
            fileName="/etc/sysconfig/network/ifcfg-${INTERFACE_NAME[$i]}";

            conf=0
            if [[ -e $fileName ]]; then                                                     # exists config file?
                  C=`$EGREP -i 'BOOTPROTO.*=.*dhcp' $fileName `                             # dhcp configured?
                  if [[ $? == 0 ]]; then                                                    # yes
                     conf=1
                  fi
            fi

            if [[ $knme == 0 && $conf == 0 ]] || [[ $knme != 0 && $conf == 1 ]]; then       # dhcp configured
               C=`$DHCPCD_TEST -t 3 ${INTERFACE_NAME[$i]} 2>/dev/null`
               R=`echo $C | grep 'offered'`
               if [[ $? == 1 ]]; then
                    writeToEliza $MSG_NO_DHCP_FOUND ${INTERFACE_NAME[$i]}                   # no dhcp found
                    if [[ $CONNECTION == $CONNECTION_WRL ]]; then
                      rc=2
                    else
                      rc=1
                    fi
               fi
            fi
         fi
      fi
      let i=i+1
   done

   state "DHCP:$rc"
   debug "<<checkDHCP $rc"

}

#################################################################################
# --- Execute dns tests
#
# --- Ping www.suse.de with it's dns name
# --- return 1 if dns ping didn't get a response
# --- return 2 if dns ping failed because of missing dns
# --- return 0 otherwise
#
#################################################################################

function checkDNS() {

	debug ">>checkDNS"

	local I
	local PING_RES
	local C
	local rc=0
	local name="www.suse.de"

# ping: unknown host www.suse.de

	C=`$PING -c 1 -W 3 $name 2>&1`
	pingRC=$?

	if [[ $pingRC == 2 ]]; then
	   	writeToEliza $MSG_CANT_LOOKUP_EXTERNAL_DNS $name
	fi

	if [[ $pingRC == 1 ]]; then
	   	writeToEliza $MSG_CANT_PING_EXTERNAL_DNS $name
	fi

   state "DNS:$pingRC"
	debug "<<checkDNS $pingRC"

return $pingRC
}

#################################################################################
#
# detect all interfaces available on system with ifconfig and identify wireless interfaces with iwconfig
#
# result: 1 based array
# INTERFACE_NO: number of interfaces detected
# INTERFACE_NAME: name of interface (ethx, wlany, ...)
# INTERFACE_IP: ipaddress of interface (empty if no IP address found)
# INTERFACE_MAC: mac address of interface
# INTERFACE_WRL_NO: number of wireless interfaces detect
# INTERFACE_RCV_ERROR: receive errors (%)
# INTERFACE_XMT_ERROR: xmit errors (%)
# INTERFACE_TYPE: either $CONNECTION_WRD or $CONNECTION_WRL
# if $INTERFACE_TYPE == $CONNECTION_WRL
# INTERFACE_ESSID: ESSID
# INTERFACE_MODE: mode of interface
# INTERFACE_ACCESS_POINT: access point mac
# INTERFACE_KEY: wireless key
#
# return number of interfaces found for the selected connection type
#
#################################################################################

function detectInterfaces () {
local q
local i
local j
local k
local rc
local interface
local element
INTERFACE_NAME=()
INTERFACE_IP=()
INTERFACE_MAC=()
INTERFACE_RCV_ERROR=()
INTERFACE_XMT_ERROR=()
INTERFACE_ESSID=()
INTERFACE_MODE=()
INTERFACE_AP=()
INTERFACE_KEY=()
INTERFACE_TYPE=()
INTERFACE_WRL_NO=0
INTERFACE_WRD_NO=0
INTERFACE_NO=0

	debug ">>detectInterfaces"

#eth0      Link encap:Ethernet  HWaddr 00:1E:37:21:38:F8
#          inet addr:192.168.0.4  Bcast:192.168.0.255  Mask:255.255.255.0
#          inet6 addr: fe80::21e:37ff:fe21:38f8/64 Scope:Link
#          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
#          RX packets:223 errors:0 dropped:0 overruns:0 frame:0
#          TX packets:208 errors:0 dropped:0 overruns:0 carrier:0
#          collisions:0 txqueuelen:100
#          RX bytes:126331 (123.3 Kb)  TX bytes:22788 (22.2 Kb)
#          Base address:0x3000 Memory:ee000000-ee020000

	# return a list of tokens
	# tokens separated by ?, list separated by %
	# return number of interfaces found
      q=`$IFCONFIG | $AWK '  BEGIN { numberOfNics=0; result=""; }
			/^.*(eth|ath|wlan|ra)[0-9].*:Ethernet/ { name = $1;
				mac = $5
				numberOfNics++;
				getline;
	# line with IPV4 infos?
				if ($1 == "inet") {
					match($2,"[0-9]+.[0-9]+.[0-9]+.[0-9]+")
					ip=substr($2,RSTART,RLENGTH);
					match($3,"[0-9]+.[0-9]+.[0-9]+.[0-9]+")
					bc=substr($3,RSTART,RLENGTH);
					match($4,"[0-9]+.[0-9]+.[0-9]+.[0-9]+")
					nm=substr($4,RSTART,RLENGTH);
					getline;
				}
	# line with IPV6 infos? - skip IPV6 infos
				if (match($0,"inet6")) {		# skip inet6 address
					getline;
				}
				getline;
				match($2,"[0-9]+")
				rcv=substr($2,RSTART,RLENGTH);
				rcv_error=0
				if (rcv > 0) {
					match($3,"[0-9]+")
					rcv_err=substr($3,RSTART,RLENGTH);
					perc=rcv_err/rcv*100;
					rcv_error = perc
				}
				getline;
				match($2,"[0-9]+")
				xmt=substr($2,RSTART,RLENGTH);
				xmt_error=0
				if (xmt > 0) {
					match($3,"[0-9]+")
					xmt_err=substr($3,RSTART,RLENGTH);
					perc=xmt_err/xmt*100;
					xmt_error=perc
				}

				if ( result != "" ) {
					result=result "%"
				}
				result=result name "?" mac "?" ip "?" rcv_error "?" xmt_error
				name=""
				mac=""
				ip=""
				rcv_error=""
				xmt_error=""
				}
			END { 	print result
				exit numberOfNics
			    }
			'`
	INTERFACE_WRD_NO=$?
	INTERFACE_NO=$INTERFACE_WRD_NO

	IFS_OLD=$IFS
	IFS="%"
	i=0
	for interface in $q; do
		let i=i+1
		INTERFACE_TYPE[$i]=$CONNECTION_WRD
		IFS="?"
		j=0
		for element in $interface; do
			case $j in
				0) INTERFACE_NAME[$i]=$element
					debug "Interface $element detected";;
				1) INTERFACE_MAC[$i]=$element
					debug "Interface ${INTERFACE_NAME[$i]}: Mac $element detected";;
            2) INTERFACE_IP[$i]=$element
					debug "Interface ${INTERFACE_NAME[$i]}: IP $element detected";;
				3) INTERFACE_RCV_ERROR[$i]=$element
					debug "Interface ${INTERFACE_NAME[$i]}: RCV $element detected";;
				4) INTERFACE_XMT_ERROR[$i]=$element
					debug "Interface ${INTERFACE_NAME[$i]}: XMT $element detected";;
				*) writeToElizaOnly $MSG_INTERNAL_ERROR;;
			esac
			let j=j+1
		done
	done
	IFS=$IFS_OLD

# eth0      no wireless extensions.

#wlan0     unassociated  ESSID:off/any
#          Mode:Managed  Frequency=nan kHz  Access Point: Not-Associated
#          Bit Rate:0 kb/s   Tx-Power:16 dBm
#          Retry limit:15   RTS thr:off   Fragment thr:off
#          Encryption key:off
#          Power Management:off
#          Link Quality:0  Signal level:0  Noise level:0
#          Rx invalid nwid:0  Rx invalid crypt:0  Rx invalid frag:0
#          Tx excessive retries:0  Invalid misc:220   Missed beacon:0

#wlan0     IEEE 802.11g  ESSID:"ESSID"
#          Mode:Managed  Frequency:2.462 GHz  Access Point: 00:14:6C:E5:F7:1F
#          Bit Rate:36 Mb/s   Tx-Power:15 dBm
#          Retry limit:15   RTS thr:off   Fragment thr:off
#          Encryption key:AAAA-BBBB-CCCC-DDDD-EEEE-FFFF-GGGG-HHHH   Security mode:open
#          Power Management:off
#          Link Quality=67/100  Signal level=-71 dBm  Noise level=-72 dBm
#          Rx invalid nwid:0  Rx invalid crypt:1  Rx invalid frag:0
#          Tx excessive retries:0  Invalid misc:240   Missed beacon:0

   q=`$IWCONFIG 2>&1 | $AWK ' BEGIN { numberOfNics=0; essid=""; result=""; }
			/^.*(eth|ath|wlan|ra)[0-9].*no wireless/ { next; }		    # skip

			/^.*(eth|ath|wlan|ra)[0-9].*.*/ {
				numberOfNics++;
				name=substr($1,1,8)	# iwconfig allows IO names > 8 chars, ifconfig allows 8 chars only
				sub("ESSID:","",$4)
			        if ( $4 == "off/any") {
		 		        essid=""
				}
			        else {
			   		gsub("\"","",$4)
					essid=$4
			        }
				getline
				sub("Mode:","",$1)
				mode=$1
				if ( $6 == "Not-Associated" || $6 == "None" ) {
					ap=""
				}
				else {
					ap=$6
				}
				getline
				getline
				getline
				sub("key:","",$2)
				if ( $2 == "off") {
					key=""
				}
				else {
					key=$2
				}

				if ( result != "" ) {
					result=result "%"
				}
				result=result name "?" essid "?" mode "?" ap "?" key
				}
			END { 	print result
				exit numberOfNics
			    }
			'`

	INTERFACE_WRL_NO=$?
	debug "Number of WLAN nics detected: $INTERFACE_WRL_NO"
	debug "iwconfig scan contents: $q"

	IFS_OLD=$IFS
	IFS="%"
	i=0
	for interface in $q; do
		let i=i+1
		IFS="?"
		j=0
		for element in $interface; do
			case $j in
				0) INTERFACE_WRL_NAME=$element;
				   debug "Interface $element detected"
				   k=1;
				   index=0
				   while [[ $k -le $INTERFACE_NO ]]; do
					if [[ ${INTERFACE_NAME[$k]} == $INTERFACE_WRL_NAME ]]; then
						debug "Found match for $element"
						index=$k
					fi
					let k=k+1
				   done
				   if [[ $index -le 0 ]]; then 			# HACK: no match to ifconfig
					let INTERFACE_NO=$INTERFACE_NO+1
					index=$INTERFACE_NO
				   	INTERFACE_NAME[$index]=$INTERFACE_WRL_NAME
				   	INTERFACE_TYPE[$index]=$CONNECTION_WRL
					debug "Added unmatched -$element-"
				   else
				   	INTERFACE_TYPE[$index]=$CONNECTION_WRL
					debug "Added matched -$element-"
				   fi
				   ;;
				1) INTERFACE_ESSID[$index]=$element
					;;
				2) INTERFACE_MODE[$index]=$element
					;;
				3) INTERFACE_AP[$index]=$element
					;;
				4) INTERFACE_KEY[$index]=$element
					;;
				*) writeToElizaOnly $MSG_INTERNAL_ERROR
					;;
			esac
			let j=$j+1
		done
	done

	IFS=$IFS_OLD

	if [[ $CONNECTION == $CONNECTION_WRL ]]; then
		rc=$INTERFACE_WRL_NO
	else
		rc=$INTERFACE_WRD_NO
	fi

# log IF states
   local i=1
   while [[ $i -le $INTERFACE_NO ]]; do
      echo "IF:${INTERFACE_NAME[$i]}  IM:${INTERFACE_TYPE[$i]}" >> $STATE
      let i=i+1
   done

state "DI:$INTERFACE_NO"
debug "<<detectInterfaces $INTERFACE_NO"

return $rc

}

#################################################################################
#
# --- Check whether there is a eth/ath/wlan/ra network interface for the connection type available.
# --- If yes,execute various tests on the interface
#
# --- Returns 2 if no IP was found
# --- Returns 1 if no network interface was found
# --- Returns 0 otherwise
#
#################################################################################

function checkNetworkInterfaces () {

debug ">>checkNetworkInterfaces"

local q
local i
local rc=1	# no IF found
local rcSub

IP_ADDRESS_FOUND=0

i=1
while [[ $i -le $INTERFACE_NO ]]; do
	if [[ $CONNECTION == $CONNECTION_WRL && ${INTERFACE_TYPE[$i]} == $CONNECTION_WRL ]] ||
			[[ $CONNECTION == $CONNECTION_WRD && ${INTERFACE_TYPE[$i]} == $CONNECTION_WRD ]]; then

		checkNetworkInterfaceCommon $i
		rcSub=$?
      state "cNiC:$i:$rcSub"
      if [[ $rcSub == 0 ]]; then    # there is an IP address and interface
         rc=0
      fi
      if [[ $rcSub == 1 ]]; then    # there is no IP address
         rc=2
      fi
	fi
	let i=i+1
done

state "NI:$rc"
debug "<<checkNetworkInterfaces $rc"

return $rc
}

#################################################################################
#
# Do some common checks
#
# return 0 if there is an ip address and return 1 if there is no IP address
#
#################################################################################

function checkNetworkInterfaceCommon () { # intecheckNetworkInterfacesrfaceIndex

debug ">>checkNetworkInterfaceCommon"

local index
local rc=0
local name
local nibble

# check whether there is a ip address on the interface
# if there is an ip address check whether there are rcv and xmit errors

index=$1
name=${INTERFACE_NAME[${index}]}

if [[ -z ${INTERFACE_IP[${index}]} ]]; then			                        # no ip address
	writeToEliza $MSG_NO_IP_ASSIGNED_TO_NIC $name
	rc=1
else
	nibble=`echo ${INTERFACE_IP[${index}]} | cut -d "." -f 1`			# check for APIPA address

	debug "--checkForAPIPAdress"

	if [[ $nibble  == 169 ]]; then
		writeToEliza $MSG_APIPA_DETECTED ${INTERFACE_IP[${index}]} $name
	fi

	debug "--checkForRCV-XMTErrors"

	if [[ ${INTERFACE_RCV_ERROR[${index}]} > $MAX_ERROR_PERCENT ]]; then		# receive errors
		writeToEliza $MSG_NIC_ERRORS $name
	else
		if [[ ${INTERFACE_XMT_ERROR[${index}]} > $MAX_ERROR_PERCENT ]]; then	# transmission errors
			writeToEliza $MSG_NIC_ERRORS $name
		fi
	fi
fi

state "NIC:$rc"
debug "<<checkNetworkInterfaceCommon $rc"

return $rc

}

#################################################################################
#
# Do some common teste for wired interfaces
#
# (empty right now)
#
#################################################################################

function checkNetworkInterfaceWrd () {
	debug ">>checkNetworkInterfacesWrd"
	rc=0
        state "NIWD:$rc"
	debug "<<checkNetworkInterfacesWrd $rc"
   return $rc
}

#################################################################################
#
# Do some common tests for wireless interfaces for HW problems
#
# Return 0 if no errors
# Return 1 if there are errors
#
#################################################################################

function checkNetworkInterfaceWrlHW () {
local rc
local finalrc=0
	debug ">>checkNetworkInterfacesWrlHW"

	if (( $USE_ROOT )); then

		checkForMissingWLANFirmware
		rc=$?
		if [[ $rc != 0 ]]; then
			writeToEliza $MSG_POSSIBLE_WLAN_FIRMWARE_PROBLEMS
			finalrc=1
		fi
	else
	      writeToEliza $MSG_NO_ANALYSIS_AS_USER "WLAN_firmware_problems"
	fi

   checkForNdisWrapperAndLinuxModule
   rc=$?
   if [[ $rc != 0 ]]; then
      finalrc=1
   fi

   checkForWLANKillSwitch
   rc=$?
   if [[ $rc != 0 ]]; then
      writeToEliza $MSG_WLAN_KILL_SWITCH_ON
      finalrc=1
   fi

   state "NIWL:$finalrc"
	debug "<<checkNetworkInterfacesWrlHW $finalrc"
   return $finalrc
}

#################################################################################
#
# Do some common tests for wireless interfaces for auth problems
#
# Return 0 if no errors
# Return 1 if there are errors
#
#################################################################################

function checkNetworkInterfaceWrlAUTH () {
local rc
local finalrc=0
	debug ">>checkNetworkInterfacesWrlAUTH"

	# check for mode set
	# if not WEP or WPA key missing

	# check for wpa_supplicant to be active and create a warning message

   state "NIWLA:$finalrc"
	debug "<<checkNetworkInterfacesWrlAUTH $finalrc"
   return $finalrc
}

#################################################################################
#
# --- Check whether there is at least one networkdevice available. Use lspci
#
# -- Return the number of devices found
#
#################################################################################

function checkForAtLeastOneNic () {

debug ">>checkForAtLeastOneNic"

local q

	if [[ $CONNECTION == $CONNECTION_WRL ]]; then
	    q=`$LSPCI | $AWK '	BEGIN { numberOfNics=0; }
			/Network.*controller/ { numberOfNics++;
				}
			END { exit numberOfNics }
			'`
	    rc=$?
	else				# wired connection
	    q=`$LSPCI | $AWK '	BEGIN { numberOfNics=0; }
			/Ethernet.*controller/ { numberOfNics++;
				}
			END { exit numberOfNics }
			'`
	    rc=$?

	fi

   state "FALON:$rc"
	debug "<<checkForAtLeastOneNic $rc"

	return $rc

}

#################################################################################
#
# --- Check whether there are multiple nics in the same subnet.
#
# --- Return 0 if no nics are in the same subnet
# --- Return 1 if there are nics in the same subnet
#
#################################################################################

function checkForNicsInSameSubnet() {

local rc
local q

debug ">>checkForNicsInSameSubnet"

    q=`$IFCONFIG  | $PERL -e 'my $nic; my %nicsFound;
#			collect all nics with their ip and netmask
			while (my $line=<STDIN>) {
#				print "$line \n";
				if ( $line=~/^([a-z0-9]+).*/) {
					$nic=$1;
				} else {
#						              $1 (ip)                  $2 (bc)                 $3 (mask)
					$line=~/.*:(\d+\.\d+\.\d+\.\d+).*:(\d+\.\d+\.\d+\.\d+).*:(\d+\.\d+\.\d+\.\d+)/;
					if ( $1 != "") {
						my @ipNibbles=split /\./, $1, 4;
						my @maskNibbles=split /\./, $3, 4;
						$netNibbles[0]=$ipNibbles[0] + 0 & $maskNibbles[0];
						$netNibbles[1]=$ipNibbles[1] + 0 & $maskNibbles[1];
						$netNibbles[2]=$ipNibbles[2] + 0 & $maskNibbles[2];
						$netNibbles[3]=$ipNibbles[3] + 0 & $maskNibbles[3];
						my $maskedIP="$netNibbles[0]\.$netNibbles[1]\.$netNibbles[2]\.$netNibbles[3]";
						$nicsFound{$nic} = $maskedIP;
#						print ".$nic,$maskedIP.";
					}
				}
				 }

#			check whether there are identical networks used by the nics
#				$nicsFound{"eth1"} = "192.168.0.0";

			my @ips=values %nicsFound;
			my @nics=keys %nicsFound;
			my $size=$#nics;
			for (my $i=0; $i<$size; $i++) {
				for (my $j=$i+1; $j<=$size; $j++) {
						if ($ips[$i] eq $ips[$j]) {
							print "$nics[$i]:$nics[$j]"
						}
				}
			}
'`
    checkForNicsInSameSubnet_Result=$q

    if [[ $q != "" ]]; then
		rc=1
    else
		rc=0;
    fi

state "NISS:$rc"
debug "<<checkForNicsInSameSubnet $rc"

return $rc

}

#################################################################################
#
# --- Check whether there are no modules loaded or any inactive modules
#
# --- Return 0 if nothing special
# --- Return 1 if there is no module loaded
# --- Return 2 if there are inactive modules
# --- Return 3 if there is no module loaded and inactive modules
#
#################################################################################

function checkModules() {
  debug ">>checkModules"

local ifce
local rc
local result

if [[ $CONNECTION == $CONNECTION_WRL ]]; then
   ifce=""
else
   ifce="eth"
fi

result=`echo $ifce |  $PERL -e'

my $active=0;
my $inactive=0;
my @inactiveName=();
my $activeName="";
my $nicName="";
my $found=0;

my $nic;
my $nicI=<>;
if ( $nicI =~ /eth/ ) {
   $nic="Ether";
}
else {
   $nic="(Network|WLAN)";
}

foreach my $line (qx §'$HWINFO' --netcard§) {

#  print $line;

   if ($line =~ /^\d+:/ && $found) {
      last;
   }
   if ($line =~ /^\d+:.+$nic/) {
      $found=1;
      next;
   }

   if ($line =~ /Driver Status: (\w+).*(not|in).*active/) {
      $inactive++;
      if (scalar @inactiveName == 0) {
         push @inactiveName,$1;
      }
      else {
         push @inactiveName,",$1";
      }
   }
      elsif ($line =~ /Driver Status: (\w+).*active/) {
      $active++;
      $activeName=$1;
   }
      elsif ($line =~ /Device File: (\w+)$/) {
      $nicName = $1;
   }
}
if ( $found ) {
   print "$nicName | $activeName | @inactiveName\n";
}
if ($activeName eq "" && scalar @inactiveName == 0) {
  exit 3
}
if ($activeName eq "") {
  exit 1
}
if (scalar @inactiveName > 0) {
  exit 2
}
exit 0'`

rc=$?

nicName=`echo $result | cut -d "|" -f 1`
active=`echo $result | cut -d "|" -f 2`
inactive=`echo $result | cut -d "|" -f 3`

if [[ $rc  == 1 || $rc == 3 ]]; then
   writeToEliza $MSG_HW_NO_ACTIVE $nicName
fi
if [[ $rc  == 2 || $rc == 3 ]]; then
   writeToEliza $MSG_HW_SOME_INACTIVE $inactive $nicName
fi
state "CM:$rc"
debug "<< checkModules $rc"
return $rc
}

#################################################################################
#
# --- Check MTU
#
#################################################################################

function checkMTU() {

debug ">>checkMTU"

local DFDetected
local testMTU
local dummy
local rc

#	detect maximum possible MTU for client or router using pppoe

	DFDetected=0
	testMTU=1600

	while [[ $DFDetected == 0 ]]; do
	 	dummy=`ping -c1 195.135.220.3 -s $testMTU -M do | $GREP "DF set"`
		DFDetected=$?
		if [[ $DFDetected == 0 ]]; then
			let testMTU=$testMTU-100
		fi
	done

	DFDetected=0
	let testMTU=$testMTU+100

	while [[ $DFDetected == 0 ]]; do
		dummy=`ping -c1 195.135.220.3 -s $testMTU -M do | $GREP "DF set"`
		DFDetected=$?
		if [[ $DFDetected == 0 ]]; then
			let testMTU=$testMTU-10
		fi
	done

	DFDetected=0
	let testMTU=$testMTU+10

	while [[ $DFDetected == 0 ]]; do
		dummy=`ping -c1 195.135.220.3 -s $testMTU -M do | $GREP "DF set"`
		DFDetected=$?
		if [[ $DFDetected == 0 ]]; then
			let testMTU=$testMTU-2
		fi
	done

	let mtuRequired=$testMTU+28

#	mtuRequired=`ping -c1 195.135.220.3 -s 1600 -M do | perl -e 'my $mtu; while(<>) { if ($_=~/mtu.* (\d+)\)/) { print "$1"};
#}'`
	defaultGatewayNic=`$ROUTE -n | $AWK '/^[0]+\.[0]+\.[0]+\.[0]+/ { print $NF; } '`
	mtuActive=`$IFCONFIG $defaultGatewayNic | $PERL -e 'my $mtu; while(<>) { if ($_=~/MTU:(\d+)/) { print "$1"}; }'`

	if [[ $mtuRequired -lt $mtuActive ]]; then
		rc=1
	else
		rc=0
	fi
   state "MTU:$rc"
	debug "<<checkMTU $rc"

}

#################################################################################
#
# --- Check whether there is a default route defined
#
# --- return
# ---    0 if there is no default route set
# ---    1 if there is a default route set
# --- and set global variable checkDefaultRoute_gateway_host to the hostname of the default gateway
# --- and set global variable checkDefaultRoute_gateway_nic to the nic which is used for the default gateway
#
#################################################################################

function checkDefaultRoute () {

debug ">>checkDefaultRoute"

local q
local i
local v
local rc

# 0.0.0.0         192.168.0.1     0.0.0.0         UG    0      0        0 eth0

    q=`$ROUTE -n | $AWK '/^[0]+\.[0]+\.[0]+\.[0]+/ { print$0; } '`

    if [[ $q == "" ]]; then
		rc=0
    else
		rc=1
	i=1
	for v in $q; do
		if [[ $i == 2 ]]; then
			checkDefaultRoute_gateway_host=$v
		fi
		if [[ $i == 8 ]]; then
			checkDefaultRoute_gateway_nic=$v
		fi

		let i=i+1
	done;
   fi
state "DR:$rc"
debug "<<checkDefaultRoute $rc"
CHECK_DEFAULT_ROUTE=$rc
return $rc

}

#################################################################################
#
# --- Cat all config files in /etc/sysconfig/network/ifcfg-*
# --- Masquerade wireless keys and passwords
#
#################################################################################

function catMyConfig() {
local C

# masquerade WLAN credentials

# BOOTPROTO='dhcp'
# BROADCAST=''
# ETHTOOL_OPTIONS=''
# IFPLUGD_PRIORITY='10'
# IPADDR=''
# MTU=''
# NAME='Intel Thinkpad  X60s, R60e model 0657'
# NETMASK=''
# NETWORK=''
# REMOTE_IPADDR=''
# STARTMODE='ifplugd'
# USERCONTROL='no'
# WIRELESS_AP=''
# WIRELESS_AUTH_MODE='open'
# WIRELESS_BITRATE='auto'
# WIRELESS_CA_CERT=''
# WIRELESS_CHANNEL=''
# WIRELESS_CLIENT_CERT=''
# WIRELESS_CLIENT_KEY=''
# WIRELESS_CLIENT_KEY_PASSWORD=''
# WIRELESS_DEFAULT_KEY='0'
# WIRELESS_EAP_AUTH=''
# WIRELESS_EAP_MODE=''
# WIRELESS_ESSID='FRAMP'
# WIRELESS_FREQUENCY=''
# WIRELESS_KEY=''
# WIRELESS_KEY_0=''
# WIRELESS_KEY_1=''
# WIRELESS_KEY_2=''
# WIRELESS_KEY_3=''
# WIRELESS_KEY_LENGTH='128'
# WIRELESS_MODE='Managed'
# WIRELESS_NICK=''
# WIRELESS_NWID=''
# WIRELESS_PEAP_VERSION=''
# WIRELESS_POWER='yes'
# WIRELESS_WPA_ANONID=''
# WIRELESS_WPA_IDENTITY=''
# WIRELESS_WPA_PASSWORD=''
# WIRELESS_WPA_PSK=''

for C in `ls /etc/sysconfig/network/ifcfg-[earwd]* 2>/dev/null`; do
	echo $SEPARATOR >> $LOG
#	processingMessage "Processing configs"
	echo "*** cat $C" >> $LOG;
	cat $C | grep -v "^#" | grep -v "^$" \
	| $AWK "BEGIN { FS=\"=\"} \
		/WIRELESS_KEY[ ]*=|WIRELESS_KEY_[0-9][ ]*=|WIRELESS_DEFAULT_KEY[ ]*|WIRELESS_KEY_LENGTH[ ]*=|\
		WIRELESS_WPA_IDENTITY[ ]*=|WIRELESS_WPA_PASSWORD[ ]*=|WIRELESS_WPA_PSK[ ]*=/ \
		{ cred=\"@@@@@@\"; \
		  if ( \$2 ~ /['\"].+['\"]/ || \$2 !~ /['\"]/ ) { \
		     if ( substr(\$2,1,1) ~ /['\"]/ ) {
			     cred=substr(\$2,1,1) cred substr(\$2,1,1);
			}
		     print \$1 \"=\" cred; next;
		   }
		}
		{ print \$0}" | $EGREP -v ".*=''" >> $LOG
done
return 0
}

#################################################################################
#
# --- Check whether ipv6 module is loaded
#
# --- return 1 if module is loaded
# --- return 0 otherwise
#
#################################################################################

function checkForIPV6() {

debug ">>checkForIPV6"

	local l

	$LSMOD | $GREP -i ipv6 > /dev/null
	rc=$?

	if [[ $rc == 0 ]]; then
		rc=1
	else
		rc=0
	fi

state "IP6:$rc"
debug "<<checkForIPV6 $rc"

	return $rc

}

#wlan0     Scan completed :
#          Cell 01 - Address: 00:14:6C:E5:F7:1F
#                    ESSID:"FRAMP"
#                    Protocol:IEEE 802.11bg
#                    Mode:Master
#                    Channel:11
#                    Frequency:2.462 GHz (Channel 11)
#                    Encryption key:on
#                    Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 6 Mb/s; 9 Mb/s
#                              11 Mb/s; 12 Mb/s; 18 Mb/s; 24 Mb/s; 36 Mb/s
#                              48 Mb/s; 54 Mb/s
#                    Quality=59/100  Signal level=-72 dBm  Noise level=-72 dBm
#                    IE: WPA Version 1
#                        Group Cipher : TKIP
#                        Pairwise Ciphers (2) : CCMP TKIP
#                        Authentication Suites (1) : PSK
#                    IE: IEEE 802.11i/WPA2 Version 1
#                        Group Cipher : TKIP
#                        Pairwise Ciphers (2) : CCMP TKIP
#                        Authentication Suites (1) : PSK
#                    Extra: Last beacon: 708ms ago
#

function detectAPs () {
local wlanif
local i
local num=0

debug ">>detectAPs $INTERFACE_NO"

i=1
while [[ $i -le $INTERFACE_NO ]]; do
	if [[ $CONNECTION == $CONNECTION_WRL && ${INTERFACE_TYPE[$i]} == $CONNECTION_WRL ]]; then
		wlanif=${INTERFACE_NAME[$i]}
		$IWLIST $wlanif scanning | $EGREP "ESSID|Channel:|Encryption|IE: [^U].*|Cypher|Quality" >> $LOG		# skip IE: Unknown
		if [[ $? == 0 ]]; then
			let num=$num+1
		fi
	fi
	let i=$i+1
done

if [[ $num == 0 ]]; then
	echo "No WLANs found" >> $LOG
fi

state "AP:$num"
debug "<<detectAPs"

}

#################################################################################
#
# --- Do common tests if a wireless interface has no IP address
#
#################################################################################

function checkNetworkInterfaceWrlNoIP () {
local rc
local q
local finalRC=0
local i
local wlanif

debug "<<checkNetworkInterfaceWrlNoIP"

i=1
while [[ $i -le $INTERFACE_NO ]]; do
   if [[ $CONNECTION == $CONNECTION_WRL && ${INTERFACE_TYPE[$i]} == $CONNECTION_WRL ]]; then
      wlanif=${INTERFACE_NAME[$i]}

      $IWLIST $wlanif scanning | $GREP "ESSID" 1>/dev/null
      if [[ $? != 0 ]]; then
         writeToEliza $MSG_WLAN_NO_SCAN $wlanif
         debug "HW/Driver problems on WLAN"
         finalRC=1

# no connection to AP

#wlan0     unassociated  ESSID:off/any
#          Mode:Managed  Frequency=nan kHz  Access Point: Not-Associated
#          Bit Rate:0 kb/s   Tx-Power:16 dBm
#          Retry limit:15   RTS thr:off   Fragment thr:off
#          Encryption key:off
#          Power Management:off
#          Link Quality:0  Signal level:0  Noise level:0
#          Rx invalid nwid:0  Rx invalid crypt:0  Rx invalid frag:0
#          Tx excessive retries:0  Invalid misc:15   Missed beacon:0

	   elif [[ ${INTERFACE_AP[$i]} == "" && ${INTERFACE_ESSID[$i]} == "" ]]; then
         writeToEliza $MSG_WLAN_AUTH_PROBS $wlanif
		   debug "Authentication problem on WLAN"
         finalRC=2

#wlan0     unassociated  ESSID:"FRAMP"
#          Mode:Managed  Frequency=nan kHz  Access Point: Not-Associated
#          Bit Rate:0 kb/s   Tx-Power:16 dBm
#          Retry limit:15   RTS thr:off   Fragment thr:off
#          Encryption key:off
#          Power Management:off
#          Link Quality:0  Signal level:0  Noise level:0
#          Rx invalid nwid:0  Rx invalid crypt:0  Rx invalid frag:0
#          Tx excessive retries:0  Invalid misc:18   Missed beacon:0

#      	elif [[ ${INTERFACE_AP[$i]} == "" && ${INTERFACE_ESSID[$i]} != "" ]]; then
#         writeToEliza $MSG_WLAN_CON_NOESSID $wlanif
#		   debug ""
#         finalRC=3
#	  fi

# connection successfully

#wlan0     IEEE 802.11g  ESSID:"FRAMP"
#          Mode:Managed  Frequency:2.462 GHz  Access Point: 00:14:6C:E5:F7:1F
#          Bit Rate:36 Mb/s   Tx-Power:15 dBm
#          Retry limit:15   RTS thr:off   Fragment thr:off
#          Encryption key:xxxx-xxxx-xxxx-xxxx-xxxx-xxxx-xxxx-xxxx   Security mode:open
#          Power Management:off
#          Link Quality=65/100  Signal level=-68 dBm  Noise level=-69 dBm
#          Rx invalid nwid:0  Rx invalid crypt:0  Rx invalid frag:0
#          Tx excessive retries:0  Invalid misc:25   Missed beacon:0

      elif [[ ${INTERFACE_AP[$i]} != "" && ${INTERFACE_ESSID[$i]} != "" ]]; then
		   debug "Connection and ESSID"
         finalRC=0
	   fi
   fi

   let i=$i+1
   done

   state "NIW:$wlanif-$finalRC"

   debug ">>checkNetworkInterfaceWrlNoIP $finalRC"

	return $finalRC

}

#################################################################################
#
# --- check if knetworkmanager is enabled and there exist configurations for wireless/wired which will be used by ifup
#
# --- return 1 if there is a configuration mismatch
# --- return 0 otherwise
# --- place in KNETWORK_IF the names of the interfaces which is misconfigured
#
#################################################################################

function checkKnetworkManager () {

debug ">>checkKnetworkManager"

	local f
	local C
	local rc
	local error=0
	local mask
	KNETWORK_IF=""

	C=`$EGREP -i 'NETWORKMANAGER.*=.*yes' /etc/sysconfig/network/config `
	rc=$?
	if [[ $rc == 0 ]]; then                                                                 # knetworkmanager enabled ?
		mask="[arwe]"                                                                   # yes
		for f in `ls /etc/sysconfig/network/ifcfg-${mask}* 2>/dev/null`; do		# no configs allowed
			error=1
			if  [[ $KNETWORK_IF == "" ]]; then
				KNETWORK_IF="${f##*-}"
			else
				KNETWORK_IF="${f##*-},$KNETWORK_IF"
			fi
		done
   else
      writeToEliza $MSG_IFUP_CONFIGURED                                                         # warning that ifup is enabled
	fi

   state "KM:$error"
	debug "<<checkKnetworkManager $error $KNETWORK_IF"

	return $error

}

#################################################################################
#
# --- check for missing firmware for WLAN cards
#
# --- return 1 if string found
#
#################################################################################

function checkForMissingWLANFirmware() {
	debug ">>checkForMissingWLANFirmware"
	local rc
	local testString
	testString="((microcode|firmware).*(failed|error|not.*found))|prism.*faulty"
	$TAIL -n $NUMBER_OF_LINES_TO_CHECK_IN_VAR_LOG_MESSAGES /var/log/messages* | $EGREP -i $testString > /dev/null
  	rc=$?

   if [[ $rc == 0 ]]; then
      rc=1
   else
      rc=0
   fi

	debug ">>checkForMissingWLANFirmware $rc"

   return $rc

}

#################################################################################
#
# --- check if the WLAN kill switch is on
#
# --- return 1 is yes
# --- return 0 otherwise
#
#################################################################################


function checkForWLANKillSwitch() {
   debug ">>checkForWLANKillSwitch"
   local rc

   `dmesg | $EGREP -i "radio.*disabled|radio.*switch.*on" > /dev/null`
   rc=$?

   if [[ $rc == 0 ]]; then
      rc=1
   else
      rc=0
   fi

   debug "<<checkForWLANKillSwitch $rc"

   return $rc
}

##################################################################################
#
#  --- Ask user for environment
#
##################################################################################

# --- Ask for the NW topology used

function getTopology () {
	local answer
	local answerNo
	local answerOffset
	TOPOLOGY=0
	TOPOLOGY_DM_LC=1
	TOPOLOGY_DR_LC=2
	TOPOLOGY_DM_LR_LC=3
	TOPOLOGY_DR_LR_LC=4
	TOPOLOGY_AP_LC=5
	TOPOLOGY_WR_LC=6
	TOPOLOGY_AP_LR_LC=7
	TOPOLOGY_WR_LR_LC=8

    writeToConsole $MSG_EMPTY_LINE
    writeToConsole $MSG_GET_TOPOLOGY

    while [[ $TOPOLOGY == 0 ]]; do
	if [[ $CONNECTION == $CONNECTION_WRD ]]; then
		writeToConsole $MSG_TOPO_DM_LC
		writeToConsole $MSG_TOPO_DR_LC
		writeToConsole $MSG_TOPO_DM_LR_LC
		writeToConsole $MSG_TOPO_DR_LR_LC
		answerNo=4
		answerOffset=0
	else
		writeToConsole $MSG_TOPO_AP_LC
		writeToConsole $MSG_TOPO_WR_LC
		writeToConsole $MSG_TOPO_AP_LR_LC
		writeToConsole $MSG_TOPO_WR_LR_LC
		answerNo=4
		answerOffset=4
	fi

	writeToConsoleNoNL $MSG_PLEASE_CORRECT_ANSWER $answerNo
	read answer
	if [[ "$answer" -le 0 || "$answer" -gt $answerNo ]]; then
		writeToConsole $MSG_UNSUPPORTED_TOPOLOGY
		answer=-1
	else
		let TOPOLOGY=answer+answerOffset
		answer=0
	fi
    done

    writeToElizaOnly $MSG_GET_TOPOLOGY
    case $TOPOLOGY in
		1) writeToElizaOnly $MSG_TOPO_DM_LC;;
		2) writeToElizaOnly $MSG_TOPO_DR_LC;;
		3) writeToElizaOnly $MSG_TOPO_DM_LR_LC;;
		4) writeToElizaOnly $MSG_TOPO_DR_LC;;

		5) writeToElizaOnly $MSG_TOPO_AP_LC;;
		6) writeToElizaOnly $MSG_TOPO_WR_LC;;
		7) writeToElizaOnly $MSG_TOPO_AP_LR_LC;;
		8) writeToElizaOnly $MSG_TOPO_WR_LR_LC;;

		*) writeToElizaOnly $MSG_INTERNAL_ERROR;;
    esac
}

# --- Ask for the NW connection used

function getConnection () {
	local answer
	CONNECTION=0
	CONNECTION_WRD=1
	CONNECTION_WRL=2

   writeToConsole $MSG_EMPTY_LINE
   writeToConsole $MSG_GET_CONNECTION

   while [[ $CONNECTION == 0 ]]; do
		writeToConsole $MSG_CON_WRD
		writeToConsole $MSG_CON_WRL
		writeToConsoleNoNL $MSG_PLEASE_CORRECT_ANSWER 2
		read answer
		if [[ "$answer" -le 0 || "$answer" -gt 2 ]]; then
			writeToConsole $MSG_UNSUPPORTED_CONNECTION
			answer=-1
		else
			CONNECTION=$answer
			answer=0
		fi
   done

   writeToElizaOnly $MSG_GET_CONNECTION
	case $CONNECTION in
		1) writeToElizaOnly $MSG_CON_WRD
			;;
		2) writeToElizaOnly $MSG_CON_WRL
			FLAGS="${FLAGS}w"	# turn on wireless outputs
			;;
		*) writeToElizaOnly $MSG_INTERNAL_ERROR
			;;
	esac
}


# --- Ask for the host the script was run on

function getExecutionHost () {

    EXECUTION_HOST_CL=1
    EXECUTION_HOST_RT=2
    EXECUTION_HOST=0

    if [[ $TOPOLOGY != $TOPOLOGY_DM_LC && $TOPOLOGY != $TOPOLOGY_DR_LC && $TOPOLOGY != $TOPOLOGY_AP_LC && $TOPOLOGY != $TOPOLOGY_WR_LC ]]; then
	    	writeToConsole $MSG_EMPTY_LINE
		writeToConsole $MSG_GET_HOST

		while [[ $EXECUTION_HOST == 0 ]]; do
			writeToConsole $MSG_HOST_CL
			writeToConsole $MSG_HOST_RT
			writeToConsoleNoNL $MSG_PLEASE_CORRECT_ANSWER 2
			read answer
			if [[ "$answer" -le 0 || "$answer" -gt 2 ]]; then
				writeToConsole $MSG_UNSUPPORTED_HOST
			else
				EXECUTION_HOST=$answer
			fi
		done
	else
		EXECUTION_HOST=$EXECUTION_HOST_CL	# has to be the client
	fi

	writeToElizaOnly $MSG_GET_HOST
	case $EXECUTION_HOST in
		1) writeToElizaOnly $MSG_HOST_CL
			;;
		2) writeToElizaOnly $MSG_HOST_RT
			;;
		*) writeToElizaOnly $MSG_INTERNAL_ERROR
			;;
	esac

}

##################################################################################
#
# --- check if WLAN should be tested but a wired connection exists
#
# --- return 1 if yes
# --- return 0 otherwise
#
##################################################################################

function checkIfWLANTestButWiredOnline () {

local i
local rc=0
local defaultGatewayNic
local foundWRLIP=0

debug ">>checkIfWLANTestButWiredOnline"

   i=1
   while [[ $i -le $INTERFACE_NO ]]; do

#      if [[ $CONNECTION == $CONNECTION_WRL && ${INTERFACE_TYPE[$i]} == $CONNECTION_WRL && ${INTERFACE_IP[$i]} != "" ]]; then
#        foundWRLIP=1
#      fi

      if [[ $CONNECTION == $CONNECTION_WRL && ${INTERFACE_TYPE[$i]} == $CONNECTION_WRD && ${INTERFACE_IP[$i]} != "" ]]; then
		  defaultGatewayNic=`$ROUTE -n | $AWK '/^[0]+\.[0]+\.[0]+\.[0]+/ { print $NF; } '`
		  if [[ $defaultGatewayNic == ${INTERFACE_NAME[$i]} ]]; then	# default GW is wired nic
			 rc=1
			 checkIfWLANTestButWiredOnline=${INTERFACE_NAME[$i]}
			 break;
		  fi
      fi
      let i=i+1
   done

#if [[ $foundWRLIP == 0 ]]; then        # no WRL IP found, then ignore an existing WRD connection
#  rc=0
#fi

debug "<<checkIfWLANTestButWiredOnline $rc"
state "WLW:$checkIfWLANTestButWiredOnline $rc"

return $rc
}

# checks whether a module is loaded
# returns 1 if module is not loaded

#Module                  Size  Used by
#nfs                   227500  1
#lockd                  63864  2 nfs
#nfs_acl                 7552  1 nfs
#sunrpc                160892  4 nfs,lockd,nfs_acl
#iptable_filter          6912  0
#ip_tables              16324  1 iptable_filter
#ip6table_filter         6784  0
#ip6_tables             17476  1 ip6table_filter
#x_tables               18308  2 ip_tables,ip6_tables

function moduleNotLoaded () {	# moduleName
local q
local rc

debug ">>moduleNotLoaded $0"

    q=`$PERL -e 'foreach (qx §'$LSMOD'§) {
			(my $module) = ($_ =~ /^(\w+) /);
			if ( $module eq $ARGV[0]) {
				print "$module\n";
				exit 0;
			}
		}
		exit 1;
		' $0`

rc=$?
debug "<<moduleNotLoaded $rc"

}

function NWElizaStates () {

debug ">>NWElizaStates `cat $STATE`"


	if (( NWELIZA_ENABLED )); then

		if [[ -z $1 ]]; then
			cat $STATE | $PERL -e 'while (<>) { s/  / /g; s/\n//; s/: /:/; print "$_ " }; print "\n"'
		else
			echo "NWElizaStates"
		fi
	fi
debug "<<NWElizaStates `cat $STATE`"

}

##################################################################################
#
# --- Check if knetworkmanager is not used whether there is a config file
#
##################################################################################

function checkNetworkManagerConfigured () {
local C
local i
local rc
local knme
local fileName

   debug ">>checkNMConfigured"

   C=`$EGREP -i 'NETWORKMANAGER.*=.*yes' /etc/sysconfig/network/config `
   knme=$?

   i=1
   while [[ $i -le $INTERFACE_NO ]]; do
      if [[ $CONNECTION == $CONNECTION_WRL && ${INTERFACE_TYPE[$i]} == $CONNECTION_WRL ]] ||
            [[ $CONNECTION == $CONNECTION_WRD && ${INTERFACE_TYPE[$i]} == $CONNECTION_WRD ]]; then

#        if [[ ${INTERFACE_IP[$i]} == "" ]]; then                                       # no IP address
            fileName="/etc/sysconfig/network/ifcfg-${INTERFACE_NAME[$i]}";

            if [[ $knme != 0 ]]; then                                                   # knetworkmanager not enabled
               if [[ ! -e $fileName ]]; then
                  writeToEliza $MSG_NO_NIC_CONFIG_FOUND ${INTERFACE_NAME[$i]}
	       fi
            fi
 #       fi
      fi
      let i=i+1
   done

   debug "<<checkNMConfigured"

}

##################################################################################
#
# --- Generate a simple tabular alphabetically sorted list of available firmware
#
##################################################################################

function listFirmware() {

  listFirmwareDirectory "/lib/firmware"

   # check for missing firmware of broadcom card (thx larry)

   dummy=`$LSPCI -nn | $GREP "14e4:43"`
   if [[ $? == 0 ]]; then
       echo "--- $1"
       listFirmwareDirectory "/lib/firmware/b43"
   fi

   dummy=`$LSPCI -nn | $EGREP "14e4:4301|14e4:4306"`
#      dummy=`lspci -nn | egrep "10de:00f1|1095:0680"`
   if [[ $? == 0 ]]; then
       echo "--- $1"
       listFirmwareDirectory "/lib/firmware/bc43legacy"
   fi
}

function listFirmwareDirectory () {
local dummy

if [[ -d $1 ]]; then

$PERL -e 'my @modules=qx "ls $ARGV[0] | sort";
            my $i=0;
            my $LIMIT=3;

            foreach my $m (@modules) {
	       chomp $m;
               printf "| %-24s","$m";
               if ( $i++ == $LIMIT ) {
                  print " |\n";
                  $i=0;
               }
            }
            if ( $i != 0 ) {
               print "|\n";
            }' $1 >> $LOG

else
    echo "$1 not found" >> $LOG
fi
}

##################################################################################
#
# --- Generate a simple tabular alphabetically sorted list of loaded modules
#
# To reduce the length of the list common non network related modules are filtered
#
##################################################################################

function listLoadedModules () {

   $PERL -e '	my @modules=qx §'$LSMOD' | sort §;
		my $i=0;
		my @modlist= qw /ata_generic auth_rpcgss autofs4 button cdrom crypto_algapi crypto_blkcipher crypto_hash cryptomgr
			 dm_crypt dm_mod exportfs ext3 ext4 fan
                	 gameport ide_core ide_pci_generic iptables ip_tables ip6_tables ip6table_raw ip6table_filter ip6table_mangle
			 iptable_filter ipt_REJECT ipt_LOG ipv6 joydev lockd
	                 loop nfs_acl nf_conntrack nf_conntrack_ipv6 nf_conntrac_netbios_ns nf_defrag_ipv4
 			 nfs nfsd nvidia parport parport_pc pata_via pcmcia pcspkr pppoe ppox
        	         processor psmouse reiserfs rtc_cmos rtc_core rtc_lib snd snd_pcm_oss snd_mixer_oss
                	 snd_sq_midi snd_seq_midi_event snd_page_alloc snd_pcm snd_seq snd_timer soundcore sunrpc usbcore usbhid videobuf_core
	                 videodev vmmon vmnet x_tables/;

		my $COLUMNS = 4;

		my %known;
		my @skipped;

		foreach my $m (@modlist) {
		        $known{$m}=1;
		}

		foreach my $module (@modules) {
			my ($m, $s, $u, $b) = ($module =~ /(\S+)\s+(\S+)\s+(\S+)(\s+(\S+))?/);
		        if ($m =~ /Module/) {
		                next;
	        	}
	        	if (exists $known{$m}) {
        		        push @skipped,$m;
		                next;
		        }
		        printf "| %-16s","$m";
		        if ( $i++ == $COLUMNS ) {
                		print " |\n";
		                $i=0;
		        }
		}
		if ( $i != 0 ) {
	        	print "|\n";
		}' >> $LOG

}

##################################################################################
#
#  --- NWEliza
#
##################################################################################

function NWEliza () {
local result
local rc
local ns
local subRC
local ip

askEliza_error=0
askEliza_warning=0
askEliza_HW_problem=0

#	checkForAtLeastOneNic
#	rc=$?
#	if [[ $rc == 0 ]]; then
#		writeToEliza $MSG_NO_NIC_FOUND
#		askEliza_HW_problem=1
#	else

# ---	Detect all available interfaces
#	detectInterfaces		done already for NWCollect
   rc=$?
   state "dI:$rc"       # number of detected NICs

# ---	check for IP address and other possible NI problems
	checkNetworkInterfaces
	rc=$?
   state "cNI:$rc"

   case $rc in

         0) # there is an ip address on the interface
            debug "--NWEliza IP found"

            # ---	Check whether an external ip address can be pinged
            checkIPPings
            rc=$?

  	    if [[ $rc == 1 ]]; then			                        # ping failure for IP
	    	checkDefaultRoute
		rc=$?
		if [[ $rc == 0 ]]; then
			writeToEliza $MSG_NO_DEFAULT_GATEWAY_SET
		else
		        writeToEliza $MSG_CHECK_DEFAULT_GATEWAY_SETTING $checkDefaultRoute_gateway_host $checkDefaultRoute_gateway_nic
                fi
	     else
	        checkDNS
	        rc=$?
    		if [[ $rc -gt 0 ]]; then			                # ping failure for DNS
			ns=`grep nameserver /etc/resolv.conf`
			subRC=$?
			if [[ $subRC != 0 ]]; then
				writeToEliza $MSG_NO_NAMESERVER_DEFINED
	                 else
        			`cat /etc/resolv.conf | awk '/nameserver/ { print $2}'`
		                 C=`$PING -c 3 -W 3 $ip 2>&1`
                		 PING_RES=`echo $C | grep " 0%"`
		                 pingRC=$?
		                 if [[ $pingRC != 0 ]]; then
                		      writeToEliza $MSG_NAMESERVER_NOT_ACCESSIBLE $ip
		                 else
                		      `dig @$ip www.suse.de | grep ";; ANSWER SECTION:"`
		                      rc=$?
                		      if [[ $rc != 0 ]]; then
		  	                  writeToEliza $MSG_NAMESERVER_NOT_VALID $ip
                        	      else
		                          writeToEliza $MSG_NAMESERVER_PROBLEM_UNKNOWN $ip
                		      fi
	               		 fi

		          fi
		    fi
 	      fi

# ---
# --- Misc other general tests if there is an ip address
# ---

	if [[ $DISTRO == $SUSE ]]; then
            checkNetworkManagerConfigured
	fi

            checkMTU
            subRC=$?

            if [[ $subRC != 0 ]]; then
               writeToEliza $MSG_POSSIBLE_MTU_PROBLEMS $mtuRequired $defaultGatewayNic $mtuActive
            fi

            checkForNicsInSameSubnet
            rc=$?

            if [[ $rc != 0 ]]; then
               writeToEliza $MSG_DUPLICATE_NETWORKS $checkForNicsInSameSubnet_Result
            fi
            ;;

         1) # no NIC
            debug "--NWEliza no valid NIC found"
            writeToEliza $MSG_NO_VALID_NI_FOUND

            if [[ $CONNECTION == $CONNECTION_WRD ]]; then
               checkNetworkInterfaceWrd
            else
               checkNetworkInterfaceWrlHW
            fi
            ;;

         2) # no IP found
            # writeToEliza (no IP found) already done before for all NICs
            debug "--NWEliza no IP found"

	if [[ $DISTRO == $SUSE ]]; then
            checkNetworkManagerConfigured
	fi

            if [[ $CONNECTION == $CONNECTION_WRD ]]; then
		if [[ $DISTRO == $SUSE ]]; then
                	checkDHCP
		fi
                checkNetworkInterfaceWrd
            else
                 checkNetworkInterfaceWrlNoIP
                 rc=$?
                 if [[ $rc == 0 ]]; then		# essid set and connected
			if [[ $DISTRO == $SUSE ]]; then
	                     checkDHCP
			fi
                 elif [[ $rc == 1 ]]; then		# HW driver problem
                      checkNetworkInterfaceWrlHW
                 elif [[ $rc == 2 ]]; then		# auth problem
                      checkNetworkInterfaceWrlAUTH
                 fi
#             analyzeSpecificNoWLANNICProblems
            fi
	if [[ $DISTRO == $SUSE ]]; then
            checkModules
	fi
            ;;

      esac

#  ---
#  --- Tests executed all the time
#  ---

   checkForIPV6
   rc=$?
   if [[ $rc != 0 ]]; then
      writeToEliza $MSG_IPV6_DETECTED
   fi

   if [[ $DISTRO == $SUSE ]]; then
	   checkKnetworkManager
	   rc=$?
	   if [[ $rc != 0 ]]; then
	      writeToEliza $MSG_KNETWORKMANAGER_ERROR $KNETWORK_IF
	   fi
   fi

  checkIfWLANTestButWiredOnline
   rc=$?
   if [[ $rc != 0 ]]; then
      writeToEliza $MSG_WLAN_WIRED_ONLINE $checkIfWLANTestButWiredOnline
   fi

  debug "<<NWEliza $askEliza_error"
  state "RTDT: $DISTRO_NAME"

  return $askEliza_error
}


##################################################################################
#
# --- check if wpa_supplicant and/or knetworkmanager process is active
#
##################################################################################

function listActiveProcesses() {
local rc
local PROCESSES="wpa_supplicant knetworkmanager nm-applet"
local p
local result=""
local o

   for p in $PROCESSES; do

      o=`ps -eo comm 2>/dev/null | $EGREP $p`
      if [[ -z $o ]]; then
         result="$result $p:NO"
      else
         result="$result $p:YES"
      fi
   done
   echo $result >> $LOG

}

##################################################################################
#
# --- check if ndiswrapper is active and in parallel a Linux driver is loaded
#
# --- return 1 if that's the case, 0 otherwise
#
# --- First suggestion to test this was from IOtz - improved version was suggested from Grothesk
#
##################################################################################

function checkForNdisWrapperAndLinuxModule {

#local linuxNativeDrivers="rt2x00usb rt73usb rt2400pci rt2500pci rt2500usb rt61pci ipw2200 bcm43xx bcm4306 ipw2100 ipw3945 p54pci ath_pci zd1211rw at76c503a rtl8187 r8187"
local rc
local q
local finalrc=0
local module
local native

debug ">>checkForNdisWrapperAndLinuxModule"

   $LSMOD | $GREP -i ndiswrapper > /dev/null
   rc=$?
   if [[ $rc != 0 ]]; then    # ndiswrapper not loaded
      state "NDIS:0"
      debug "<<checkForNdisWrapperAndLinuxModule 0"
      return 0;
   fi

#ts154usb : driver installed
#        device (083A:4501) present (alternate driver: p54usb)

   module=`ndiswrapper -l | $PERL -e '<>=~/(\w+)\s+:/; print "$1";'`                            # get module name used in ndiswrapper

   native=`ndiswrapper -l | $PERL -e 'while (<>) {          # get native driver
        if ($_=~/alternate driver: (\w+)/) {
                print "$1"; leave;
        }
   }'`

# ts154usb : driver installed
# device (083A:4501) present (alternate driver: p54usb)

   ndiswrapper -l  | $GREP -i "alternate driver" > /dev/null
   rc=$?

   if [[ $rc == 0 ]]; then
      writeToEliza $MSG_NDISWRAPPER_PROB $module $native
      finalrc=1;
   fi

   ndiswrapper -l | $GREP -i "driver invalid" > /dev/null
   rc=$?

   if [[ $rc == 0 ]]; then
      writeToEliza $MSG_NDISWRAPPER_FW_PROB $module
      finalrc=1;
   fi

# kernel ndiswrapper version 1.47 loaded (smp=yes)
# kernel: usb 5-7: reset high speed USB device using ehci_hcd and address 8
# kernel: ndiswrapper (check_nt_hdr:150): kernel is 64-bit, but Windows driver is not 64-bit;bad magic: 010B
# kernel: ndiswrapper (load_sys_files:216): couldn't prepare driver 'sis163u'

   if (( $USE_ROOT )); then

	  $GREP -i "ndiswrapper.*bad magic.*" 2>&1 1>/dev/null /var/log/messages
	   rc=$?

	  if [[ $rc == 0 ]]; then
	      writeToEliza $MSG_NDISWRAPPER_ARCH_PROB $module
	      finalrc=1;
	  fi
   else
      writeToEliza $MSG_NO_ANALYSIS_AS_USER "ndiswrapper_arch_problems"
  fi

   state "NDIS:$finalrc"
   debug "<<checkForNdisWrapperAndLinuxModule $finalrc"
   return $finalrc;

}

##################################################################################
#
# --- Extract some useful info from hwinfo (SUSE only)
#
##################################################################################

function listHWInfo() {

debug ">>listHWInfo"

if [[ $DISTRO == $SUSE ]]; then

	if [[ -z $1 ]]; then

		$PERL -e '

		 my $MATCH = qr /Model:|Vendor:|Device:|Driver:|Driver Modules:|Subvendor:|Subdevice:|Device File:|^\d+:|Link detected|Driver Status:|Driver Activation Cmd:/;
		 my $line;

  	         foreach $line (`'$HWINFO' --netcard`) {
        	   if ($line =~ /$MATCH/) {
		      print "$line";
        	   }
		 }
		'
	else
		echo "hwinfo (filtered)"
	fi

fi

debug "<<listHWInfo"

}

##################################################################################
#
# Extract some info from /etc/sysconfig/network (SUSE only)
#
##################################################################################

function listSuSEConfig() {

debug ">>listSuSEConfig"

if [[ $DISTRO == $SUSE ]]; then
	if [[ -z $1 ]]; then
		$EGREP -i "persistent|networkmanager" /etc/sysconfig/network/config | $GREP -v "^#\|^$"
	else
		echo "egrep -i \"persistent|networkmanager\" /etc/sysconfig/network/config | grep -v \"^#|^$\""
	fi

fi
debug "<<listSuSEConfig"

}

##################################################################################
#
#  -- Masquerade sensitive informations
#
##################################################################################

#
# This function masquerades mac addresses
#
# All identical macs get the same masqueraded values so xref is possible
#

function masqueradeMacs() {

debug ">>masqueradeMACs"

cat $FINAL_RESULT | $PERL -e '

my $MAC_ADDRESS = qr /(([\da-fA-F]{2}\:){5}[\da-fA-F]{2})/;
my $MAC_MASK="#";
my $mac_cnt=0;
my %macAddresses;

while (<>) {

    $line=$_;
    pos($line)=0;

    while ($line =~ /($MAC_ADDRESS)/g) {

	  my $mac = $1;
          my $privateMac = $mac;
	  my $normalizedMac = uc($mac);

          if ( $macAddresses{$normalizedMac} ) {
                $privateMac = $macAddresses{$normalizedMac};        # get masqueraded mac
          }
          else {
            $mac_cnt++;
            $privateMac =~ s/\w/$MAC_MASK/g;
#           $privateMac =~ s/(.)./$1$MAC_MASK/g;
            $privateMac =~ s/$MAC_MASK$/$mac_cnt/;
            $macAddresses{$normalizedMac} = $privateMac;        # cache mac
          }
          s/$mac/$privateMac/;
      }
   print "$_";
}

exit $mac_cnt;

' > $FINAL_RESULT_mm_$$

# writeToEliza $MSG_MASQ_MAC $?

mv $FINAL_RESULT_mm_$$ $FINAL_RESULT

debug "<<masqueradeMACs"

}

#
# This function masquerades ESSIDs
#
# All identical ESSID get the same masqueraded values so xref is possible
#

function masqueradeESSIDs() {

debug ">>masqueradeESSIDs"

cat $FINAL_RESULT | $PERL -e '

my $ESSID_MASK="Â§Â§Â§Â§Â§Â§Â§Â§";
my $essid_cnt=0;
my %essidAddresses;
my $tick=chr(0x27); 	# tick mark

while (<>) {

#	iwcsan			ifcfg
    if (/ESSID:"(.+)"/ || /WIRELESS_ESSID=${tick}(.+)${tick}/ ) {

          my $essid = $1;
          my $privateEssid = $essid;

          if ( $essidAddresses{$essid} ) {
                $privateEssid = $essidAddresses{$essid};        # get masqueraded essid
          }
          else {
            $essid_cnt++;
#            $privateEssid = "${ESSID_MASK}${essid_cnt}";
            $privateEssid =~ s/(.)./$1#/g;
            $essidAddresses{$essid} = $privateEssid;            # cache essid
          }
         s/$essid/$privateEssid/;
      }
   print "$_";
}

exit $essid_cnt;

' > $FINAL_RESULT_ee_$$

# writeToEliza $MSG_MASQ_ESSID $?

mv $FINAL_RESULT_ee_$$ $FINAL_RESULT

debug "<<masqueradeESSIDs"

}

#
# This function masquerades IPs
#
# All private IP addresses (e.g. 192er numbers, 10er numbers etc) are NOT masqueraded
## All identical ips get the same masqueraded values so xref is possible
#

function masqueradeIPs() {

debug ">>masqueradeIPs"

cat $FINAL_RESULT | $PERL -e '

my $IP_ADDRESS = qr /(([\d]{1,3}\.){3}[\d]{1,3})/;
my $IP_MASK="%";
my $ip_cnt=0;
my %ipAddresses;
my $line;
my $route_flag=0;
my $line_cnt;
my $inBlock=0;

while (<>) {

    if ($_ =~ "\\*\\*\\* (route|ifconfig|iwconfig|cat /etc/hosts|cat /etc/resolv|cat /etc/sysconfig/network/ifcfg)") {
	$inBlock=1;
    }

    if ($_ =~ "=====") {			                # route block (and others) ends
	$inBlock=0;
    	$route_flag=0;
    }

   if ( $inBlock == 1) {

    if ($_ =~ "\\*\\*\\* route") {		                # route block starts
	$route_flag=1;
    }

    $line=$_;
    pos($line)=0;
    $line_cnt=0;

    while ($line =~ /($IP_ADDRESS)/g ) {

    	if ($_ =~ "Ping of") {		                	# external ping
		next;
    	}

          my $ip = $1;
          $line_cnt++;

          my $privateIp = $ip;
          if ( $` =~ /Mask[e]?/) {				# skip mask in ifconfig (German and English locale)
               next;
          }

 	  if ($route_flag == 1 && $line_cnt==3) {		# skip mask in route command
		next;
	  }

          if ( $1 !~ /^192\.168\./
            && $1 !~ /^127\./
            && $1 !~ "0\.0\.0\.0"
            && $1 !~ "^169\."
            && $1 !~ "^10\."
            && $1 !~ "^172\.([1][6-9]|2[1-9]|3[0-1])" ) {

              if ( $ipAddresses{$ip} ) {
                $privateIp = $ipAddresses{$ip};                 # get masqueraded ip
              }
              else {
                $ip_cnt++;
                $privateIp =~ s/\d/$IP_MASK/g;
                $privateIp =~ s/$IP_MASK$/$ip_cnt/;
                $ipAddresses{$ip} = $privateIp;                 # cache ip
              }
              s/$ip/$privateIp/;
          }
      }
  }
  print "$_";
}

exit $ip_cnt;

' > $FINAL_RESULT_mi_$$

# writeToEliza $MSG_MASQ_IP $?

mv $FINAL_RESULT_mi_$$ $FINAL_RESULT

debug "<<masqueradeIPs"

}

function stripWLANKeys () {
   $PERL -e 'while (<>) {
        if (/\S+/) {
                print "$_";
        }
      }' $1
}


##################################################################################
#
# --- Helperfunctions
#
##################################################################################

function stripEmptyLines () {
   $PERL -e 'while (<>) {
        if (/\S+/) {
                print "$_";
        }
      }' $1
}

function joinLines () {
   $PERL -e 'while (<>) {
               chomp;
               print "$_ ";
            }' $1
}

function stripWLANKeys() {

$PERL -e '

$mask="@@@@@@";
%keywords = ( "WIRELESS_KEY" => 1,              # SUSE -> /etc/sysconfig/network/ifcfg-*
             "WIRELESS_DEFAULT_KEY" => 1,
             "WIRELESS_KEY_LENGTH" =>1,
             "WIRELESS_WPA_IDENTITY" => 1,
             "WIRELESS_WPA_PASSWORD" => 1,
             "WIRELESS_WPA_PSK" => 1,
             "KEY" => 1,                        # RedHat -> /usr/share/doc/initscripts*/sysconfig.txt
             "wpa-psk" => 1,                    # Debian -> /etc/network/interfaces
             "wireless-key" => 1,
                                                # Arch ->
             "WLAN_KEY" => 1,                   # Slackware -> /etc/rc.d/rc.inet1.conf
             "WPAPSK" => 1,
        );


while (<>) {
        my ($key,$value) = /(\w+).*=.*['\''"](\S*)['\''"]/;
        if ($value) {
                if ( exists($keywords{$key})) {
                        s/$value/$mask/;
                }
        }
        print;
}' $1

}
#################################################################################
#
# NWCollect: List network configuration
#
##################################################################################

function listNetworkConfigs () {

local cmd

cmd=("cat /etc/sysconfig/network/ifcfg-[earwd]* | egrep -v \".*=''\"" # SUSE
     "cat /etc/sysconfig/network-scripts/ifcfg-[earwd]* | egrep -v \".*=''\"" #REDHAT
     "cat /etc/network/interfaces | $GREP -v \"^#\|^$\"" # DEBIAN
     "cat /etc/rc.conf | $GREP -v \"^#\|^$\"" # ARCH
     "cat /etc/rc.d/rc.inet1.conf | $GREP -v \"^[ ]*#\|^$\"") # SLACKWARE

	if [[ -z $1 ]]; then
		eval ${cmd[$DISTRO]} | stripWLANKeys
	else
		echo ${cmd[$DISTRO]}
	fi
}

##################################################################################
#
#  --- Collect PD data
#
##################################################################################

#
# --- Commands executed collect valuable informations about the network and it's configuration
#
function collectNWData () {	#listOnly

debug ">>collectNWData"

# standard
i=0;FLAG[$i]="s";MSG[$i]="uname -a";CMD[$i]="uname -a"
#i=$i+1;FLAG[$i]="s";MSG[$i]="cat /etc/*-release";CMD[$i]="cat /etc/*-release"
#i=$i+1;FLAG[$i]="s";MSG[$i]="cat /etc/*[-_]version || cat /etc/*[-_]release";CMD[$i]="cat /etc/*[-_]release || cat /etc/*[-_]version"
i=$i+1;FLAG[$i]="s";MSG[$i]="cat /etc/*[-_]release || cat /etc/*[-_]version";CMD[$i]="(ls /etc/*[-_]release 2>/dev/null && cat /etc/*[-_]release) || (ls /etc/*[-_]version && cat /etc/*[-_]version)"
i=$i+1;FLAG[$i]="s";MSG[$i]="cat /etc/resolv | grep -i \"nameserver\"";CMD[$i]="cat /etc/resolv.conf | $GREP -v \"^#\|^[ ]*$\" | $GREP -i \"nameserver\""
i=$i+1;FLAG[$i]="s";MSG[$i]="cat /etc/hosts";CMD[$i]="cat /etc/hosts | $GREP -v \"^#\|^$\" | $GREP -v \"::\""
#i=$i+1;FLAG[$i]="s";MSG[$i]="cat /etc/HOSTNAME";CMD[$i]="cat /etc/HOSTNAME"
i=$i+1;FLAG[$i]="s";MSG[$i]="route";CMD[$i]="$ROUTE -n"
i=$i+1;FLAG[$i]="l";MSG[$i]="arp";CMD[$i]="$ARP -n"
i=$i+1;FLAG[$i]="s";MSG[$i]="ifconfig";CMD[$i]="$IFCONFIG | stripEmptyLines"
i=$i+1;FLAG[$i]="s";MSG[$i]="ping tests";CMD[$i]="pingTests"
i=$i+1;FLAG[$i]="s";MSG[$i]="";CMD[$i]="dhcpTests"
# hardware
i=$i+1;FLAG[$i]="h";MSG[$i]="lspci";CMD[$i]="$LSPCI -nn | $EGREP -i '(ethernet|network).*controller'"
i=$i+1;FLAG[$i]="h";MSG[$i]="lsusb";CMD[$i]="which lsusb 2>/dev/null 1>&2 && lsusb;which lsusb 2>/dev/null 1>&2 || echo \"lsusb not available. usbutils package needs to be installed\""
#i=$i+1;FLAG[$i]="h";MSG[$i]="hwinfo --netcard # (filtered)";CMD[$i]="hwinfo"
i=$i+1;FLAG[$i]="h";MSG[$i]="";CMD[$i]="listHWInfo"
i=$i+1;FLAG[$i]="h";MSG[$i]="lsmod # (filtered)";CMD[$i]="listLoadedModules"
# firewall
i=$i+1;FLAG[$i]="f";MSG[$i]="iptables -L -vn";CMD[$i]="$IPTABLES -L -vn"
i=$i+1;FLAG[$i]="f";MSG[$i]="SuSE firewall configuration";CMD[$i]="cat /etc/sysconfig/SuSEfirewall2 | $GREP -v \"^#|^$\""
i=$i+1;FLAG[$i]="f";MSG[$i]="iptables -t nat -L";CMD[$i]="$IPTABLES -t nat -L"
# sysconfigs
#i=$i+1;FLAG[$i]="c";MSG[$i]="Network config";CMD[$i]="cat /etc/sysconfig/network/config | $GREP -v \"^#|^$\""
#i=$i+1;FLAG[$i]="c";MSG[$i]="Sysctl";CMD[$i]="cat /etc/sysconfig/sysctl | grep -v \"^#|"^$\""
#i=$i+1;FLAG[$i]="c";MSG[$i]="dhcp definitions";CMD[$i]="cat /etc/sysconfig/network/dhcp | $GREP -v \"^#|^$\""
#i=$i+1;FLAG[$i]="c";MSG[$i]="proxy definitions";CMD[$i]="cat /etc/sysconfig/proxy | $GREP -v \"^#|^$\""
#i=$i+1;FLAG[$i]="c";MSG[$i]="ssh definitions";CMD[$i]="cat /etc/sysconfig/ssh | $GREP -v \"^#|"^$\""
#i=$i+1;FLAG[$i]="c";MSG[$i]="cat /etc/sysconfig/network/ifcfg-[earwd]* | egrep -v \".*=''\"";CMD[$i]="catMyConfig"
i=$i+1;FLAG[$i]="s";MSG[$i]="";CMD[$i]="listNetworkConfigs"
# router settings
i=$i+1;FLAG[$i]="r";MSG[$i]="IP forwarding";CMD[$i]="cat /proc/sys/net/ipv4/ip_forward"
# wireless
#	mask encryption key if present
#	"Encryption key:xx xxx-xxxx-xxxx-xxxx-xxxx-xxxxxxx   Security mode:open"
#	"Encryption key:off   Security mode:open"
i=$i+1;FLAG[$i]="w";MSG[$i]="iwconfig";CMD[$i]="$IWCONFIG 2>&1 |stripEmptyLines | $SED \"s/\(Encryption key:\)\([^o][^f][^f][^ ]*\)\(.*\)/\1@@ @@@-@@@@-@@@@-@@@@-@@@@-@@@@@@@\3/\""
# grep area for messages
i=$i+1;FLAG[$i]="w";MSG[$i]="Actual date for bias of following greps";CMD[$i]="echo \"`date +\"%T %F\"`\" 1>&2"
i=$i+1;FLAG[$i]="w";MSG[$i]="grep -i radio /var/log/messages* | tail -n 5";CMD[$i]="[ $UID -eq 0 ] && ( $GREP -i radio /var/log/messages* | $TAIL -n 5 ); [ $UID -ne 0 ] && echo \"Unable to grep -i radio /var/log/messages* as normal user\""
i=$i+1;FLAG[$i]="w";MSG[$i]="dmesg | grep -i radio | tail -n 5";CMD[$i]="dmesg | $GREP -i radio | $TAIL -n 5"
i=$i+1;FLAG[$i]="w";MSG[$i]="tail -n $NUMBER_OF_LINES_TO_CHECK_IN_VAR_LOG_MESSAGES /var/log/messages* | $GREP -i firmware | tail -n 5";CMD[$i]="[ $UID -eq 0 ] && (tail -n $NUMBER_OF_LINES_TO_CHECK_IN_VAR_LOG_MESSAGES /var/log/messages* | $GREP -i firmware | $TAIL -n 5); [ $UID -ne 0 ] && echo \"Unable to grep -i firmware /var/log/messages* as normal user\""
i=$i+1;FLAG[$i]="w";MSG[$i]="ls /lib/firmware/*";CMD[$i]="listFirmware /lib/firmware"
#i=$i+1;FLAG[$i]="w";MSG[$i]="ls /lib/firmware";CMD[$i]="ls -Rxw 120 /lib/firmware | grep -v \"^$\""
i=$i+1;FLAG[$i]="w";MSG[$i]="ndiswrapper -l";CMD[$i]="( $LSMOD | $GREP -i ndiswrapper > /dev/null ) && ndiswrapper -l; ( $LSMOD | $GREP -i ndiswrapper > /dev/null ) || echo \"No ndiswrapper module loaded\""
i=$i+1;FLAG[$i]="w";MSG[$i]="Active processes";CMD[$i]="listActiveProcesses"
#i=$i+1;FLAG[$i]="w";MSG[$i]="grep NETWORKMANAGER /etc/sysconfig/network/config";CMD[$i]="$GREP NETWORKMANAGER /etc/sysconfig/network/config | $GREP -v \"^#\""
#i=$i+1;FLAG[$i]="w";MSG[$i]="grep -i persistent /etc/sysconfig/network/config";CMD[$i]="$GREP -i persistent /etc/sysconfig/network/config | $GREP -v \"^#|^$\""
i=$i+1;FLAG[$i]="w";MSG[$i]="";CMD[$i]="listSuSEConfig"
# first rule for SuSE 10.2 and below, second for SuSE 10.3 and above
i=$i+1;FLAG[$i]="w";MSG[$i]="grep 'eth|ath|wlan|ra' /etc/udev/rules.d/*net_persistent* /etc/udev/rules.d/*persistent-net*";CMD[$i]="$EGREP 'eth|ath|wlan|ra' /etc/udev/rules.d/*net_persistent* /etc/udev/rules.d/*persistent-net* 2>/dev/null | $GREP -v \":#\|:$\" 2>/dev/null"
i=$i+1;FLAG[$i]="w";MSG[$i]="grep -r 'eth[0-10]|ath[0-10]|wlan[0-10]|ra[0-10]' /etc/modprobe.*";CMD[$i]="$EGREP -r 'eth[0-10]|ath[0-10]|wlan[0-10]|ra[0-10]' /etc/modprobe.*|$GREP -v '#\|blacklist'"
i=$i+1;FLAG[$i]="w";MSG[$i]="iwlist scanning";CMD[$i]="detectAPs"

let NUMBER_OF_TESTS=$i

i=0

while [ -n "${CMD[$i]}" ]; do

#	echo $FLAGS ${FLAG[$i]}
	R=`echo $FLAGS | grep "${FLAG[$i]}"`

	if [[ $? == 0 ]]; then
		processingMessage $i $NUMBER_OF_TESTS "${MSG[$i]}"
#		fill log file with information
		debug "*** ${CMD[$i]} "
		if [[ -z ${MSG[$i]} ]]; then
			msg=`eval ${CMD[$i]} m`
			if [[ -z $msg ]]; then			# no report for this distro
				let i=i+1
				continue
			fi
			echo $SEPARATOR >> $LOG
			echo "*** $msg" >> $LOG
			debug "-- $msg"
		else
			echo $SEPARATOR >> $LOG
			echo "*** ${MSG[$i]}" >> $LOG
			debug "-- ${MSG[$i]}"
		fi
		eval ${CMD[$i]} 2>> $LOG 1>> $LOG
	fi
	let i=i+1

done
processingMessage 0
debug "<<collectNWData"
}

# help text

function usage () { # exitcode

  echo $VERSION_STRING $COPYRIGHT
  echo "Analyze system for common network configuration problems"
  echo "and collect network problem determination information for futher problem determination"
  echo "Invocation: $MYSELF"
  echo "Parameters:"
  echo "-d : Write debug messages"
  echo "-f : Firewall rules and SuSE firewall configurations are included"
  echo "-h : Print this help message"
  echo "-l : Create long output which includes output of arp and /etc/hosts"
  echo "-n : Turn NWEliza off"
  echo "-o filename : Filename of result file (default: collectNWData.txt)"
  echo "-r : Router flag is included"
  echo "-u : Don't run script as root"
  echo "-x : Trace script flow. Creates huge output"

  if [[ -z $1 ]]; then
    exit 0
  else
    exit $1
  fi
}

#################################################################################
#################################################################################
#################################################################################
####
####                                 main
####
#################################################################################
#################################################################################
#################################################################################

# write warning because script runs on a non SuSE distro

#if [[ ! -e /etc/SuSE-release ]]; then
#	writeToConsole $MSG_MAIN_SUSE_ONLY
#	writeToConsole $MSG_MAIN_SUSE_ONLY
#	writeToConsole $MSG_MAIN_SUSE_ONLY
#fi

##################################################################################
#
# handle invocation options
#
##################################################################################

# defauls

DEBUG="off"
TRACE=0
FLAGS="-shc"                                        # default flags
opt=$1
NWELIZA_ENABLED=1				    # enabled for all distros
USE_ROOT=1			 		    # default: Call script as root
USE_USER_AS_PARM=0

# parse args

while getopts ":l :f :r :u :d :x :h :o: :n" opt
do case "$opt" in
   l) FLAGS="${FLAGS}l";;
   f) FLAGS="${FLAGS}f";;
   r) FLAGS="${FLAGS}r";;
   d) DEBUG="on";;
   n) NWELIZA_ENABLED=0;;
   u) USE_USER_AS_PARM=1;;
   o) OUTPUT_FILE=$OPTARG;;
   h) usage 1;;
   \?) echo "Unknown option \"-$OPTARG\"."
         usage 1;;
   :) echo "Option \"-$OPTARG\" requires an argument."
         usage 1;;
    esac
done

if (( ! $USE_USER_AS_PARM )); then		# invocation not as normal user requested
	if [ $UID -eq 0 ]; then			# invoked by root already
	   USE_ROOT=1
	else
	   answer=""				# ask user for his choice
	   while [[ $answer == "" ]]; do
		writeToConsoleNoNL $MSG_ASK_FOR_ROOT
		read answer
		case "$answer" in
			[yYjJ]) answer="Y";;
			[nN]) answer="N";;
			*) answer="";;
		esac
	   done
	   if [[ $answer == "n" || $answer == "N" ]]; then
	      USE_ROOT=0
	   else
	      USE_ROOT=1
	   fi
	fi
else
	USE_ROOT=0
fi

writeToConsole $MSG_EMPTY_LINE

#  invoke script as root if requested

if (( $USE_ROOT )); then
	if [ $UID -ne 0 ]; then
	   INVOCATION_DIR=`pwd`
	   echo $VERSION_STRING
	   writeToConsole $MSG_MAIN_BECOME_ROOT
	   su -c "$0 $*"
	   exit $?
	fi
fi

shift $(($OPTIND - 1))				# pop invocation parms

# check whether all required progs are available and locate their path

if [[ $DISTRO == $SUSE ]]; then
	MODS=$MODS_SUSE
else
	MODS=$MODS_OTHER
fi

for mod in $MODS; do
#	echo "--------- $mod"
	 # prog name in lower case
	lwr=`echo $mod | perl -e "print lc(<>);"`
	mod=`echo $mod | sed 's/-/_/'`
   	# store detected path
	if (( $USE_ROOT)); then
		eval "$mod=$(which $lwr 2>/dev/null)"
	else
	   	p=`find {/sbin,/usr/bin,/usr/sbin,/bin} -name $lwr | head -n 1`
#		echo "------> $p"
  		eval "$mod=\"${p}\""
	fi
	eval "c=\${${mod}}"
#	echo "**** Mod: $lwr MOD: $mod C: $c"
	if [ ! -x "$c" ]; then
		writeToConsole $MSG_MAIN_PROG_REQUIRED $lwr
		exit 1
	 fi
done

if [[ $TRACE != 0 ]]; then
	set -o verbose
	set -o xtrace
fi

#################################################################################
# --- Now do your job
#################################################################################

rm $FINAL_RESULT 2>/dev/null
writeToEliza $MSG_MAIN_VERSION $VERSION_STRING

if [[ $DISTRO == $UNKNOWN_DISTRO ]]; then
    writeToEliza $MSG_DISTRO_NOT_SUPPORTED
    exit 1
fi

if [[ $DISTRO == $SUSE ]]; then
   NWELIZA_ENABLED=1
fi

if (( ! $USE_ROOT )); then
	writeToEliza $MSG_ANALYSIS_AS_USER
fi

getConnection
getTopology
getExecutionHost

writeToConsole $MSG_EMPTY_LINE
writeToConsole $MSG_START_COLLECTING $FINAL_RESULT_SHORT_NAME
detectInterfaces
collectNWData
writeToConsole $MSG_EMPTY_LINE

if (( $NWELIZA_ENABLED )); then
	writeToConsole $MSG_ELIZA_START_ANALYZE
	writeToConsole $MSG_EMPTY_LINE
	NWEliza
else
	writeToConsole $MSG_NWELIZA_UNAVAILABLE
fi

#################################################################################
# --- Paperwork
#################################################################################

if [[ $DISTRO != $SUSE ]]; then
	writeToEliza $MSG_CHECK_KEYS $FINAL_RESULT_SHORT_NAME
fi
#writeToConsole $MSG_EMPTY_LINE

if (( $NWELIZA_ENABLED )); then

	if [[ $askEliza_error == 0 && $askEliza_warning == 0 ]]; then
		writeToEliza $MSG_MAIN_NO_ERROR_DETECTED $FINAL_RESULT_SHORT_NAME
	else
		writeToEliza $MSG_MAIN_GOTO_LINK
	fi
fi

writeToEliza $MSG_MAIN_POST_FILE $FINAL_RESULT_SHORT_NAME

echo $CODE_BEGIN >> $FINAL_RESULT

if (( $NWELIZA_ENABLED )); then
	cat $ELIZA_RESULT >> $FINAL_RESULT
	echo $SEPARATOR >> $FINAL_RESULT
fi

cat $LOG >> $FINAL_RESULT

if (( $NWELIZA_ENABLED )); then
	echo "$SEPARATOR" >> $FINAL_RESULT
	echo "*** `NWElizaStates m`" >> $FINAL_RESULT
	echo "`NWElizaStates`" >> $FINAL_RESULT
fi

echo $CODE_END >> $FINAL_RESULT

#
# masquerade IPs and macs
#

masqueradeMacs
masqueradeIPs
masqueradeESSIDs

#       give ownership of file back to user

if [ $CND_USER != "root" ]; then
  chown $CND_USER.users $FINAL_RESULT                   # give created file back to owner
fi

# delete all temporary files

cleanupTempFiles

#

if [[ -n $OUTPUT_FILE ]]; then
	OUTPUT_FILE="collectNWData_${OUTPUT_FILE}${FLAGS}.txt"
	mv $FINAL_RESULT $OUTPUT_FILE
fi
