#!/bin/bash
# Usage: install.sh
#
# Description:
# -----------------------------------
# Global functions and variables for the installscript
#
# 2007-06-06 by Bjarke Bruun/Excitor
#
# Version: 0.5.5-01
#

dmeInstallHelp() 
{
	echo "DME Installer version `head $0 | grep Version: | cut -d":" -f2 | sed "s, [ ]*,,g"`"
	echo "Copyright 2007-, Excitor A/S, Denmark, info@excitor.com"
	echo ""
	echo "Options are:"
	echo " -u=<username>"
	echo " --username=<username>     Set the username that is passed to the dme-install.sh script"
	echo	
	echo " -p=<password>"
	echo " --password=<password>     Set the password that is passed to the dme-install.sh script"
	echo
	echo " --version=<number>        Choose this item from the version list when asked during installation"
	echo "                           Cannot choose eg. \"3.0-SP3\""
	echo
	echo " --type=<number>           Value can be:"
	echo "                               0 for manual choise of --version option"
	echo "                               1 for default --version=1 - aka latest with MySQL support"
	echo "                               2 for default --version=2 - aka latest with MS SQL support"
	echo
	echo " --menu=<number>"
	echo " --mainmenu=<number>       Choose the main menu item eg. 1 or C or K for 'Install', 'Connector install'"
	echo "                           or 'Kannel install'"
	echo
	echo " --conmenu=<number>"
	echo " --conmenu=<number>        Choose the Connector menu item eg. 1 for newest version of the connector that is available"
	echo "                           Please bear in mind that 3.0 and 3.5 Connectos are available"
	echo " --conconnect=<string>     Set the IP or hostname the Connector is to connect to when started"
	echo " --conname=<string>        Set the name the Connector will be installed as and show up as on the DME webinterface"     
	echo
	echo
	echo " --answer"
	echo " --answer=true"
	echo " --autoanswer=true         This option will automaticly choose the default option in menues and "
	echo "                           and questions, but not when a version it choosen"
	echo
	echo " --startdme=[true|false]   Default value: false"
	echo "                           If set to true, then the installed DME instance will be started"
	echo "                           If set to false, then the installed DME instance will not be started" 
	echo
	echo "DME 3.x specific:"
	echo "Certificate settings"
	echo " --setcn=<value>           Set the CN value for the certificate, defaults to the IP of the DME server"
	echo " --setc=<value>            Set Country code for certificate, default is DK"
	echo " --setou=<value>           Set Organization Unit default is 'DME'"
	echo " --seto=<value>            Set Organization Name, default is empty"
	echo " --setst=<value>           Set State, default is empty"
	echo " --setl=<value>            Set Locality name, default is empty"
	echo " --setemail=<email>        Set the email address for the certificate"
	echo " --certok                  If this option is set, then the certificate will be auto accepted if the"
	echo "                           CN, C and email is set. Will not accept certificate details if they are"
	echo "                           not provided."
	echo
	echo "Database related:"
	echo " --dbhost=<value>          Set the hostname or IP of the database server"
	echo " --dbname=<value>          Set the database name to use"
	echo " --dbusername=<username>   Set the username to use for the database connection"
	echo " --dbpassword=<password>   Set the password for the above username"
	echo " --dbport=<value>          Set the port number to use for the connection"
	echo "                              MySQL port is : 3306"
	echo "                              MS SQL port is: 1433"
	echo " --db-migrate              Re-run the DME 3.6 SP1 database migration"
	echo
	echo "Extra parameters:"
	echo "New versions or beta versions"
	echo " --beta                    This parameter will enable DME versions that are currently in beta"
	echo "To get more verbose output from the installer "
	echo " --debug                   This parameter will enable you to see more onscreen about what the"
	echo "                           installer does. All this information is located in the dme-install.log"
	echo "                           file in /tmp/dme_install/log/"
	echo
	echo "Example"
	echo "Here is an example to install the latest DME version with local MySQL DBMS without user input."
	echo "The example is for a user with DME install login 'john' and password 'doe' and a certificate details "
	echo "for a dummy domain eg dme.example.com. (a \\ is an indication that the line below is to be appended without"
    echo "line break)"
	echo 
	echo "  sh dme-install.sh -u=john -pdoe --menu=1 --version=1 \\"
	echo "      --setemail=admin@example.com --setcn=dme.example.com \\"
	echo "      --certok --answer=true"
	echo
	echo "The same can be used for a MS SQL DBMS on some IP with dme/password as credentials and 'dme' as DB name. This is done by chaning the"
	echo "parameter '--version' to 2 and adding the --db* parameters. eg:"
	echo 
	echo "  sh dme-install.sh -u=john -pdoe --menu=1 --version=2 \\"
	echo "      --setemail=admin@example.com --setcn=dme.example.com \\"
	echo "      --certok --answer=true \\"
	echo "      --dbhost=172.16.10.10 --dbport=1433 --dbname=dme --dbusername=dme --dbpassword=password"
	echo
	echo "The above MS SQL example can also be used with a remote MySQL database if the '--version' parameter is set to 1"
    echo "and the '--dbport' is set to 3306, or what ever port the MySQL server is configured to use." 
	echo
	exit 0	
}

VERSION=`grep Version: $0 | head -n1 | cut -d: -f2 | sed "s,^ [ ]*,,g"` 
CWD=`pwd`
########### DEVELOPMENT/TEST MODE  ############
#if [ ! -d /var/dme/instances/base ]
#then
#	rm -rf /tmp/dme_install/tmp
#	rm -rf /tmp/dme_install/files/*sh
#	rm -rf /tmp/dme_install/files/requir*
#fi
########### DEVELOPMENT/TEST MODE  ############


# Global settings
JBOSS_HOME="/usr/local/jboss"
JBOSS_USER="jboss"
JBOSS_GROUP="jboss"
JBOSS_VERSION=$b_jboss



# Min and max db-connections
MINPOOLSIZE=50
MAXPOOLSIZE=200
# JBoss Permsize 
PERMMIN=128
PERMMAX=192
# JBoss heap size
XMS=512
XMX=1280
# JBoss thread size
THREADSIZE=320

# Default certificate values
company="Unknown";
orgUnit="Unknown";
cityLoc="Unknown";
stateProv="Unknown";
country="DK";



# Prepare commandline parameters for easy use (C style)
argc=$#
count=0
SCRIPTNAME=${SCRIPTNAME:-`basename $0`}
LOCALINSTALL=${LOCALINSTALL:-"false"}
	
# Create logs and temporary directories
START_PWD=`pwd`
TMPDIR=${TMPDIR:-"/tmp/dme_install"}

MAINLOG="$TMPDIR/logs/dme-install.log"
WGETLOG="$TMPDIR/tmp/current_file_download.log" # download log
LOGINFO="true"



log4bash(){ 
   #validate the parameters
   if [ ${#} -lt 2 ] ;then
      echo "FATAL ERROR: you must pass at least 2 arguments to ${FUNCNAME}"
      return 1
   fi

   case ${1} in
   *[!0-9]*|"")
      echo "FATAL ERROR: 1st parm passed to ${FUNCNAME} must be NUMERIC"
      return 1
      ;;
   esac

   l4b_last_label=${#L4B_LABEL[@]}
   if [ ${l4b_last_label:-0} -gt 0 ] ;then
      (( l4b_last_label-=1 ))
   fi
   if [ ${1} -lt 0 -o ${1} -gt ${l4b_last_label:-0} ] ;then
      echo "FATAL ERROR: 1st parm passed to ${FUNCNAME} must be between 0 and ${l4b_last_label:-0}"
      return 1
   fi

   #write the message to the logfile, if appropriate
   if [ ${1} -ge ${L4B_DEBUGLVL:-"0"} ] ;then
      #prep the log message, timestamp string and log file name
      L4B_LOGTIME=`${L4B_DATE:-"date"} "${L4B_DATEFORMAT:-"+%Y-%m-%d %H:%M:%S.%N"}"`
      L4B_MESSAGE=`echo "${L4B_LOGTIME}${L4B_DELIM:-" "}${L4B_LABEL[${1}]:-"UNKNOWN"}${L4B_DELIM:-" "}${3:-"unknown"}(${4:-"?"}) ${2}"`
      L4B_LOGGER=${L4B_LOGFILE:-$MAINLOG}

      if [[ ${L4B_VERBOSE:-"false"} == true ]] ;then
         echo "${L4B_MESSAGE}"|tee -a ${L4B_LOGGER}
      else
         echo "${L4B_MESSAGE}" >> ${L4B_LOGGER}
      fi
   fi
   return 0
} #log4bash 

# Create tmp installation directories
mkdir -p "$TMPDIR/logs"  2> /dev/null 
mkdir -p "$TMPDIR/tmp"   2> /dev/null
mkdir -p "$TMPDIR/files" 2> /dev/null

# parse the command line options given to this script
L4B_VERBOSE=${L4B_VERBOSE:-"false"}
if [ "$DEBUG" == "true" ]
then
	L4B_DEBUGLVL=0
else
	L4B_DEBUGLVL=1
fi


# set L4B_LABEL array, if it has not already been set
if [ ${#L4B_LABEL[@]} -eq 0 ] ;then
   declare -a L4B_LABEL=(DEBUG INFO WARN ERROR CRITICAL FATAL)
fi

# initialize the L4B_* variables
for LabelIndex in $(seq 0 $((${#L4B_LABEL[@]}-1))) ;do
   declare L4B_${L4B_LABEL[${LabelIndex}]}=${LabelIndex}
done
# Clear old files (don't remove the release-X.Y.Z directories)
rm -rf $TMPDIR/tmp/*
rm -rf $TMPDIR/scripts/*
rm -rf $TMPDIR/files/*sh
rm -rf $TMPDIR/files/required_files.sh

# Supported distributions (Only tested on RHEL4)

FC5="Fedora Core release 5 (Bordeaux)"
FC7="Fedora release 7 (Moonshine)"
FC8="Fedora release 8 (Werewolf)"
FC9="Fedora release 9 (Sulphur)"
FC10="Fedora release 10 (Cambridge)"
FC11="Fedora release 11 (Leonidas)"
FC13="Fedora release 15 (Lovelock)"

SUSE10="SUSE Linux Enterprise Server 10"
SUSE11="SUSE Linux Enterprise Server 11"

RHEL4="Red Hat Enterprise Linux ES release 4"
RHEL4AS="Red Hat Enterprise Linux AS release 4"
RHEL4ES="Red Hat Enterprise Linux ES release 4"

RHEL5="Red Hat Enterprise Linux ES release 5"
RHEL5S="Red Hat Enterprise Linux Server release 5"
RHEL5AS="Red Hat Enterprise Linux AS release 5"
RHEL52="Red Hat Enterprise Linux Server release 5.2"
RHEL53="Red Hat Enterprise Linux Server release 5.3"
RHEL54="Red Hat Enterprise Linux Server release 5.4"

RHEL6="Red Hat Enterprise Linux Server release 6"

# Unsupported distroes that will be supported in the future 
CENTOS5="CentOS release 5"
UBUNTU8="Ubuntu 8"
UBUNTU9="Ubuntu 9"
UBUNTU10="Ubuntu 10"

#ALL_DISTROS="CENTOS5 FC5 FC7 FC8 FC9 FC10 SUSE10 RHEL4 RHEL4AS RHEL4ES RHEL5 RHEL5S RHEL5AS RHEL5ES RHEL52"
ALL_DISTROS="CENTOS5 FC7 FC8 FC9 FC10 FC11 FC13 SUSE10 SUSE11 RHEL4 RHEL4AS RHEL4ES RHEL5 RHEL6 RHEL5S RHEL5AS RHEL52 UBUNTU10"
SUPPORTED_DISTROS=( FC7 FC8 FC9 FC10 FC11 FC13 SUSE10 SUSE11 RHEL4 RHEL5 RHEL6 UBUNTU8 UBUNTU9 UBUNTU10 )

# Kannel version to install/upgrade to	
KVERSION="1.4.1"

DEBUG=${DEBUG:-"false"}
UPGRADEDEBUG=${UPGRADEDEBUG:-"false"}
NOSTART=${NOSTART:-"true"}
TESTINSTALL=${TESTINSTALL:-"true"}
MINDISKSIZE=20
if [ "$DEBUG" == "true" ]
then
	MINDISKSIZE="5"
	log4bash 0 "Minimum disksize is set to ${MINDISKSIZE}Gb"
fi
echo "Min disksize set to: ${MINDISKSIZE}Gb"
installServer=${installServer:-"install.excitor.dk"}
installPath=""
RESUME="$TMPDIR/do_not_touch" # File to save settings for installation

# Set colors to make reading output from the script easier
GOOD="\e[32;40m"
WARN="\e[33;40m"
BAD="\e[31;40m"
HILITE="\e[36;40m"
BRACKET="\e[34;40m"
NORMAL="\e[37;40m"


# Error code checking 
E_NETWORK=${E_NETWORK:-"false"}

# Misc global variables
WAIT_MENU=${WAIT_MENU:-5}
WAIT_READ=${WAIT_READ:-60}
USERNAME="false"
PASSWORD="false"


DEV="false"
BETA="false"
OLDVERSIONS="false"
		
# Parse command line options
for x in ${@}
do
	case $x in
		-h|--help) dmeInstallHelp; exit ; ;;
		--debug) DEBUG="true" ;;
		--upgradedebug) UPGRADEDEBUG="true" ;;
		--dev) DEV="true" ;;
		--beta) BETA="true" ;;
		--old) OLDVERSIONS="true" ;;
		-u=*|--username=*) USERNAME=`echo $x | cut -d"=" -f2` ;;
		-p=*|--password=*) PASSWORD=`echo $x | cut -d"=" -f2` ;;
		--version=*)       CHOOSEVERSION=`echo $x | cut -d"=" -f2` ;;
		--menu=*|--mainmenu=*) MAINMENU=`echo $x | cut -d"=" -f2 | cut -d" " -f1` ;;
		--conmenu=*) CONMENU=`echo $x | cut -d"=" -f2 | cut -d" " -f1` ;;
		--conconnect=*) CONNECTORIP=`echo $x | cut -d"=" -f2 | cut -d" " -f1` ;;
		--conname=*) CONNECTORNAME=`echo $x | cut -d"=" -f2 | cut -d" " -f1` ;;
		--contype=*) 
				CONNECTORTYPE=`echo $x | cut -d"=" -f2 | cut -d" " -f1 | tr '[:upper:]' '[:lower:]'`
				case $CONNECTORTYPE in
					e|exc|exchange) CONNECTORTYPE=E ;;
					d|dom|domino) CONNECTORTYPE=D ;;
					*) unset CONNECTORTYPE ;;
				esac
		;;
		--insmenu=*) INSMENU=`echo $x | cut -d"=" -f2 | cut -d" " -f1` ;;
		--insname=*) INSNAME=`echo $x | cut -d"=" -f2 | cut -d" " -f1` ;;
		--insif=*) INSIF=`echo $x | cut -d"=" -f2 | cut -d" " -f1` ;;
		--insip=*) INSIP=`echo $x | cut -d"=" -f2 | cut -d" " -f1` ;;
		--insmask=*) INSMASK=`echo $x | cut -d"=" -f2 | cut -d" " -f1` ;;

		--autoanswer=*|--answer=*) DEFAULTANSWER=`echo $x | cut -d"=" -f2 | cut -d" " -f1` ;;
		--nostart)
			NOSTART=`echo $x | cut -d"=" -f2 | cut -d" " -f1`
			case $NOSTART in
				false)	NOSTART="true" ;;
				true)	NOSTART="false" ;;
			esac	
		;;
		--start=*) START=`echo $x | cut -d"=" -f2 | cut -d" " -f1` ;;
		--clean=*) CLEAN=`echo $x | cut -d"=" -f2 | cut -d" " -f1` ;;
		--debug) DEBUG="true" ;;
		--disksize=*) MINDISKSIZE=`echo $x | cut -d"=" -f2 | sed "s,[^0-9],,g" | cut -d" " -f1` ;;
		--dbhost=*)     DBHOST=`echo $x | cut -d"=" -f2-` ;;
		--dbport=*)     DBPORT=`echo $x | cut -d"=" -f2-` ;;
		--dbusername=*) DBUSERNAME=`echo $x | cut -d"=" -f2-` ;;
		--dbpassword=*) DBPASSWORD=`echo $x | cut -d"=" -f2-` ;;
		--dbname=*)     DBNAME=`echo $x | cut -d"=" -f2-` ;;
		--db-restart*) 
			RESTART=true
		;;
		--setcn=*)	setTmpCN=`echo $x | cut -d"=" -f2-` ;;
		--setc=*)	setTmpC=`echo $x | cut -d"=" -f2-` ;;
		--setou=*)	setTmpOU=`echo $x | cut -d"=" -f2-` ;;
		--seto=*)	setTmpO=`echo $x | cut -d"=" -f2-` ;;
		--setemail=*)	setTmpemailAddress=`echo $x | cut -d"=" -f2-` ;;
		--setst=*)	setTmpST=`echo $x | cut -d"=" -f2-` ;;
		--setl=*)	setTmpL=`echo $x | cut -d"=" -f2-` ;;
		--distro=*) CHOOSEDISTRO=`echo $x | cut -d"=" -f2-` ;;
		#--connectorip=*|-cip=*) CONNECTORIP=`echo $x | cut -d"=" -f2-` ;;
		#--connectorname=*|-cname=*) CONNECTORNAME="`echo "$x" | cut -d"=" -f2-`" ;;
		--autosign*)
			if [[ $x == *=* ]]
			then
				AUTOSIGN=`echo $x | cut -d"=" -f2`
			else
				AUTOSIGN=true
			fi
		;;
		--certok*)
			CCONTINUE=c
			case $CCONTINUE in
				c|C) echo "Will automaticly aprove certificate details" ;;
			esac
		;;
	esac
done

if [ "$DEBUG" == "" ]
then
	white "USERNAME: $USERNAME"
	white "PASSWORD: $PASSWORD"
	sleep 1
fi

	
	
detect_arch()
{
	log4bash 0 "detect_arch()" ${FUNCNAME} ${LINENO}
	# Uname -m seems to be the most reliable option
	ARCH=`uname -m`
	log4bash 0 " - architecture: $ARCH" ${FUNCNAME} ${LINENO}
}
detect_distribution()
{
	log4bash 0 "detect_distribution()" ${FUNCNAME} ${LINENO}
	detect_arch
	# Uname -m seems to be the most reliable option
	DISTRO=""
	for D in $ALL_DISTROS
	do
		dwhite "  - checking for distro: $D"
		local pattern=$(eval echo \$$D)
		#check=`head -n1 /etc/issue | grep "$pattern"`
		check=`grep "$pattern" /etc/issue`
		if [ "$check" == "" ]
		then
			if [ -e /etc/redhat-release ]
			then
				dwhite "Checking /etc/redhat-release for $D distro information"
				check=`grep "$pattern" /etc/redhat-release`
			fi
			if [ -e /etc/SuSE-release ]
			then
				dwhite "Checking /etc/SuSE-release for $D information"
				check=`grep "$pattern" /etc/SuSE-release`
			fi
			if [ -e /etc/debian_version ] && [ -e /etc/lsb-release ]
			then
				dwhite "Checking for debian version/variant for $D information"
				check=`grep "$pattern" /etc/lsb-release`
			fi
		fi
		log4bash 0 "Checking for distribution: \"$pattern\"" ${FUNCNAME} ${LINENO}
		if [ "$check" != "" ]
		then
			DISTRO="$D"
			#log4bash 0 "Found: \"$D\"" ${FUNCNAME} ${LINENO}
			dwhite "Found: \"$D\"" ${FUNCNAME} ${LINENO}
			break
		else
			if [ "`grep "$SUSE10" /etc/issue`" != "" ]
			then
				DISTRO="$SUSE10"
			fi
		fi

	done
	if [ "`echo "$DISTRO" | grep RHEL4`" != "" ]
	then
		dwhite " - simpilfying \$DISTRO variable: RHEL4"
		DISTRO="RHEL4"
	fi
	if [ "`echo "$DISTRO" | grep RHEL5`" != "" ]
	then
		dwhite " - simpilfying \$DISTRO variable: RHEL5"
		DISTRO="RHEL5"
	fi
	

	DISTRIBUTION=$DISTRO
	dwhite "Distribution set to: \"$DISTRO\"" ${FUNCNAME} ${LINENO}
	# Settting easy distro variable
	if [ "`echo $DISTRO | grep "RHEL4"`" != "" ]
	then
		DISTRO="RHEL4"
	fi
	if [ "`echo $DISTRO | grep "RHEL5"`" != "" ]
	then
		DISTRO="RHEL5"
	fi
	if [ "$DISTRO" == "" ]
	then
		DISTRO="unknown"
	fi
	log4bash 0 " - distribution found: $DISTRO" ${FUNCNAME} ${LINENO}
}

usingDistro()
{
	log4bash 1 "Specific for: $DISTRO" ${FUNCNAME} ${LINENO}
}

enterContinue()
{
	local asdf
	if [ "$1" == "" ]
	then
		whiten "Press <Enter> to continue"
	else
		whiten "${1}"
	fi
	if [ "$DEFAULTANSWER" != "true" ] 
	then
		read asdf
		unset asdf
	else 
	 	white " <Enter> has been pressed"
	fi
}
enterReturn()
{
	local asdf
	whiten "Press <Enter> to return"
	read asdf
	unset asdf
}

denterReturn()
{
	if [ "$DEBUG" == "true" ]
	then
		dwhiten "ONLY FOR DEBUG: "
		enterReturn
	fi
}
denterContinue()
{
	if [ "$DEBUG" == "true" ]
	then
		dwhiten "ONLY FOR DEBUG: "
		enterReturn
	fi
}
error() 
{
	echo ""
	echo -e "${BAD} Error message:${NORMAL}"
	echo -e "${BAD}  - $1 ${NORMAL}"
	echo ""
	log4bash 3 "Error to user:" 
	log4bash 3 "====================================" 
	log4bash 3 "====================================" 
	log4bash 3 "${1}" 
	log4bash 3 "====================================" 
	log4bash 3 "====================================" 

	if [ "$E_NETWORK" != "false" ]
	then
		normal "If the problem with the connection to the download server persists, "
		normal "then please contact DME support with detailed information in the "
		normal "log file at: $MAINLOG"
		normal ""
		normal "This script keeps a log of the installation so you have a detailed view of "
		normal "what happend if things go wrong and you need help from DME support."
		normal ""
		normal "Thanks"
		normal ""
	fi

	if [ "$EXIT" == "truee" ]
	then
		# if the call to log4bash 3 is via _exit() then provide some extra information to support 
		log4bash 1 "DO NOT EDIT BELOW THIS LINE!\n************************ IMPORTANT INFORMATION FOR SUPPORT ********************************" ${FUNCNAME} ${LINENO}
		log4bash 1 "Distribution: $DISTRIBUTION" ${FUNCNAME} ${LINENO}
		log4bash 1 "Script executed by: `whoami`" ${FUNCNAME} ${LINENO}
		log4bash 1 "`/sbin/ifconfig`" ${FUNCNAME} ${LINENO}
		log4bash 1 "System variables\n" ${FUNCNAME} ${LINENO}
		log4bash 1 "`set`" ${FUNCNAME} ${LINENO}
		log4bash 1 "Currently running processes" ${FUNCNAME} ${LINENO}
		log4bash 1 "`ps xauwww`" ${FUNCNAME} ${LINENO}
		log4bash 1 "************************ IMPORTANT INFORMATION FOR SUPPORT ********************************" ${FUNCNAME} ${LINENO}
	fi
}



warn()   { echo -e "${WARN}${1}${NORMAL}"; log4bash 2 "$1" ${FUNCNAME} ${LINENO}; }
warnn()  { echo -n -e "${WARN}${1}${NORMAL}"; log4bash 2 "$1" ${FUNCNAME} ${LINENO}; }

ewarn()
{
	echo ""
	echo -e "${WARN} Setup information:${NORMAL}"
	echo -e "${WARN}  - $1 ${NORMAL}"
	echo ""
	log4bash 2 "$1" ${FUNCNAME} ${LINENO}
}
_exit()
{
	EXIT='true'
	if [ "$1" != "" ]
	then
		error "$1"
	fi
	warn "You can find a log of the installation in $MAINLOG for more information"
	log4bash 1 "Quitting via _exit()" 
	log4bash 1 "Time: `date`" 
	normal
	remove_logs
	# Return to last directory
	cd $START_PWD
	if [ "$DWLINK" != "" ]
	then
		rmDownloadLink
	fi
	exit 1
}
goodn()    { echo -n -e "${GOOD}${1}${NORMAL}"; }
good()     { echo -e "${GOOD}${1}${NORMAL}"; }
normaln()  { echo -n -e "${HILITE}${1}${NORMAL}"; }
normal()   { echo -e "${HILITE}${1}${NORMAL}"; }
whiten()   { echo -n -e "${NORMAL}${1}${NORMAL}"; }
white()    { echo -e "${NORMAL}${1}${NORMAL}"; }

# Debug output to the screen if DEBUG
dnormal()  { if [ "$DEBUG" == "true" ]; then normal  "${1}"; fi;  log4bash 1 "$1" $2 $3; }
dnormaln() { if [ "$DEBUG" == "true" ]; then normaln "${1}"; fi;  log4bash 1 "$1" $2 $3; }
bwhite()   { white   "${HILITE}${1}${NORMAL}";  log4bash 1 "$1" $2 $3; }
bwhiten()  { whiten  "${HILITE}${1}${NORMAL}";  log4bash 1 "$1" $2 $3; }
dwhite()   { if [ "$DEBUG" == "true" ]; then white   "${HILITE}${1}${NORMAL}"; fi; log4bash 1 "$1" $2 $3; }
dwhiten()  { if [ "$DEBUG" == "true" ]; then whiten  "${HILITE}${1}${NORMAL}"; fi; log4bash 1 "$1" $2 $3; }
dwarn()    { if [ "$DEBUG" == "true" ]; then warn    "${HILITE}${1}${NORMAL}"; fi; log4bash 2  "$1" $2 $3; }
dwarn()    { if [ "$DEBUG" == "true" ]; then warnn   "${HILITE}${1}${NORMAL}"; fi; log4bash 2 "$1" $2 $3; }
ddwhite()   { if [ "$UPGRADEDEBUG" == "true" ]; then white   "${HILITE}${1}${NORMAL}"; fi; log4bash 1 "$1" $2 $3; }
ddwhiten()  { if [ "$UPGRADEDEBUG" == "true" ]; then whiten  "${HILITE}${1}${NORMAL}"; fi; log4bash 1 "$1" $2 $3; }
copy() {
	if [ "$?" != "0" ]
	then
		warn 
		warn
		warn "!!! COMMAND DID NOT COMPLETE SUCCESSFULLY !!!"
		warn 
		warn
	fi

}
topScreen() 
{
	log4bash 0 "topScreen()" ${FUNCNAME} ${LINENO}
	# Present the user with some informaiton no a clear screen
	clear
	# Default to the generic DME installation screen
	if [ "$1" == "" ]
	then
		TEXT="DME Server Installation"
	else
		TEXT="$1"
	fi
	log4bash 0 "************************************************************" 
	log4bash 0 "***                                                      ***" 

	clear
	whiten ""
	white "************************************************************"
	white "***                                                      ***"
	

	for TEXT in "${@}"
	do
		LEN="${#TEXT}"
		LENMAX=`expr $LEN + 10`
		for x in $(seq $LEN 49); do TEXT="$TEXT "; done
		white "`echo "***  TEXT  ***" | sed "s,TEXT,$TEXT,g" ; if [ "$?" != "0" ]; then echo "error: $TEXT"; fi`"
		log4bash 0 "`echo "***  TEXT  ***" | sed "s,TEXT,$TEXT,g" ; if [ "$?" != "0" ]; then echo "error: $TEXT"; fi`" ${FUNCNAME} ${LINENO}
	done


	white "***                                                      ***"
	white "************************************************************"
	log4bash 0 "***                                                      ***" 
	log4bash 0 "************************************************************" 
	white
}



report_distro_unsupported()
{
	topScreen "DME Server Installation"
	error "Your combination of Linux distribution and architechture is not supported"
	error "Unsupported GNU/Linux distribution.\n  - Please use one of the following"
	#    *Red Hat Enterprise 4\n    *Red Hat Enterprise 5\n\t*Fedora Core 8\n    *Fedora Core 9\n    *SuSE Linux Enterprise Server 10"
	for x in ${SUPPORTED_DISTROS[@]}
	do
		a=$(eval echo \$$x)
		white "${BAD}\t* $a"
	done
	white "$NORMAL"
	if [ "$DWLINK" != "" ]
	then
		rmDownloadLink
	fi
	exit 1
}

isInteger()
{
	case $1 in
		*[!0-9]*|"") ISINTEGER=false;;
		*) ISINTEGER=true;;
	esac
}

clrscr() {

	# Clear the screen if the NOCLEAR is not set to true
	if [ "$NOCLEAR" != "true" ]
	then
		clear
	else
		dwhite "<clrscr() called>" $FUNCNAME $LINENO  ${FUNCNAME} ${LINENO}
	fi
}

dmeHelp() {
	# This is a wrapper for the /bin/less program to display 
	# a help message based on the search term in "$1"
	if [ "$1" != "" ]
	then
		rm -f $TMPDIR/files/helptext.txt 2> /dev/null
		download "linux/scripts/helptext.txt" 
		case $DISTRO in
		SUSE10|SUSE11|FC9|FC10)
			less -c -d -i -K -L -~ -P"---- Press q or Q to return from help ----" --pattern="$1" "$TMPDIR/files/helptext.txt"
		;;
		*)
			less -c -d -i -L -~ -P"---- Press q or Q to return from help ----" --pattern="$1" "$TMPDIR/files/helptext.txt"
		;;
	esac
	fi
	topScreen "Please wait while returning to the" "installation system"
}

doStart()
{

	log4bash 1 "Starting the installation at `date`" 
	log4bash 1 "`head -n10 dme-install.sh 2> /dev/null | grep "Version:" | sed "s,# ,,g"`"
	topScreen "Please wait while initializing"
	log4bash 0 "doStart()" ${FUNCNAME} ${LINENO}
	# first function to call
	
	log4bash 1 "----------------------------------------------------------" ${FUNCNAME} ${LINENO}

	log4bash 0 " - checking for root privileges" ${FUNCNAME} ${LINENO}
	if [ "`whoami`" != "root" ]
	then
		echo "`basename $0` must be run by the root user"
		exit 1
	fi

	# SELinux check !!!
	# In the future create rules for the installation and DME to run with SELinux
	log4bash 0 " - SELINUX check" ${FUNCNAME} ${LINENO}
	if [ -e /usr/sbin/sestatus ] && [ "`/usr/sbin/sestatus | grep "SELinux status:" | grep "disabled"`" == "" ]
	then
		warn "The installation cannot continue due to SELinux"
		warn "  - Please disable SELinux by"
		warn "    - adding \"selinux=0\" as a parameter to the bootloader"
		_exit "SELinux does not allow for MySQL to be installed correctly.\nThe installation will abort until SELinux has been disabled!"
	else	
		white "SELinux not enabled - will continue the installation"
	fi

	VERSIONSFILTER="\"type_filter"
	if [ "$OLDVERSIONS" != "true" ]
	then
			VERSIONSFILTER="$VERSIONSFILTER\|OLD"
	fi
	VERSIONSFILTER="$VERSIONSFILTER\""
	dwhite "  VERSIONSFILTER=$VERSIONSFILTER"	


	# Check for different tools used during the installation
	log4bash 0 " - utility check" ${FUNCNAME} ${LINENO}
	white "Checking system for misc tools used during installation:"
	which apt-get 1> /dev/null 2> /dev/null
	if [ "$?" == "1" ]
	then
		for x in tar zip unzip ln mv cp wget gzip gunzip rpm find bc at
		do
			dwhite "    $x" $FUNCNAME $LINENO ${FUNCNAME} ${LINENO}
			if [ "`which $x 2> /dev/null`" == "" ]
			then
				log4bash 0 " - $x not found" ${FUNCNAME} ${LINENO}
				_exit "The tool \"$x\" is not installed"
			fi
		done
	else
		for x in tar zip unzip ln mv cp wget gzip gunzip find bc at
		do
			dwhite "    $x" $FUNCNAME $LINENO ${FUNCNAME} ${LINENO}
			which $x 1> /dev/null 2> /dev/null
			if [ "$?" != "0" ]
			then
				log4bash 0 " - $x not found" ${FUNCNAME} ${LINENO}
				warn "  - \"$x\" not found"
				exitDEB=true
			fi
		done
		if [ "$exitDEB" == "true" ]
		then
			warn "Please install the packages above"
			exit 1
		fi
	fi

	# Remove old installation log
	#rm -f $MAINLOG
	
	# a few variables that are handy for choosing which distribution
	# and version of the installation files are needed 
	detect_arch
	detect_distribution 
	# Hack for FC13 - run as FC11
	if [ "$DISTRO" == "FC13" ]; then DISTRO="FC11"; fi 
		
	# Do specific distribution things before continuing
	 
	case $DISTRO in
	RHEL4|RHEL5|RHEL6)			
		# Architecture: Red Hat Enterprise Linux 4 and 5
		case $ARCH in
			i586|i686) ARCH=i386 ;;
		esac
		;;
	FC5|FC7) 
		# Architecture: Fedora Core 5
		case $ARCH in
			i586|i686|x86_64) ARCH=i386 ;;

		esac
		;;
	FC8|FC9|FC8|FC10|FC11|FC13)
		case $ARCH in
			i586|i686) ARCH=i386 ;;
			x86_64) ARCH=x86_64 ;;
		esac
		;;
	FC3|RHEL3)
		# Architecture: Fedorea Core 3 and Red Hat Enterprise Linux 3
		warn "!!! This distribution is not supported !!!"
		log4bash 1 "!!! This distribution is not supported !!!" ${FUNCNAME} ${LINENO}
		log4bash 1 "Distribution found is: $DISTRO"  ${FUNCNAME} ${LINENO}
		sleep 1
		[ $ARCH = "x86_64" ] && report_distro_unsupported
		case $ARCH in
			i586|i686|x86_64) ARCH=i386 ;;
		esac
		exit 1
	        ;;
	SUSE10|SUSE11)
		# Architecture: SuSE Enterprise Linux 10
		#[ $ARCH = "x86_64" ] && report_distro_unsupported
		case $ARCH in
			i586|i686) ARCH=i386 ;;
		esac
		;;
	CENTOS5)
		case $ARCH in 
			i586|i686) ARCH=i386 ;;
		esac
	;;
	UBUNTU8|UBUNTU9|UBUNTU10)
		warn "UBUNTU 8-9-10 support is limited" ; sleep 2;
	;;
	*)
		[ $ARCH = "x86_64" ] && report_distro_unsupported
		if [ `echo $distro|grep -c "Red Hat Enterprise Linux"` -eq 1 ]
		then
			kannel_version="1.4.0-9_1"
			install_sqlite
			install_postgresql_libs
			install_mysql_libs
		else
			topScreen "DME Server Installation"
			cat /etc/issue
			error "This Linux distribution version is unsupported. $DISTRO $ARCH"
			_exit "Unsupported GNU/Linux distribution.\n  - Please use one of the following\n    *Red Hat Enterprise 4\n    *Red Hat Enterprise 5\n    *Fedora Core 5, 7 to 11\n    *SuSE Linux Enterprise Server 10, 11"
			exit 1
		fi
		;;
	esac
	log4bash 0 " - architecture overrided to: $ARCH" ${FUNCNAME} ${LINENO}
	case $DISTRO in
		CENTOS4|CENTOS5|RHEL4|RHEL5|FC5|FC7|FC8|FC9|FC10)
			YUM=`find /etc -iname 'yum.conf'|head -n1`
			if [ -e $YUM ]
			then
				log4bash 0 " - setting up YUM override for JDK and MySQL" ${FUNCNAME} ${LINENO}
				dwhite "Checking for yum update settings in $YUM" ${FUNCNAME} ${LINENO}
				exclude=`grep "exclude=" $YUM 2> /dev/null`
				if [ "`echo $exclude | cut -d"=" -f2-`" != "" ]
				then
					ex=`echo "$exclude" | cut -d"=" -f2-`
					dwhite "  exclude is set" ${FUNCNAME} ${LINENO}
					MYSQLEXCLUDED="false"
					JDKEXCLUDED="false"
					for x in ${ex[@]}
					do
						# check for MySQL exclusion
						if [ "`echo $x | grep -i ^mysql`" != "" ]
						then
							MYSQLEXCLUDED="true"
						fi
						if [ "`echo $x | grep -i ^jdk`" != "" ]
						then
							JDKEXCLUDED="true"
						fi
					done
					if [ "$MYSQLEXCLUDED" != "true" ]
					then
						white "  - updating $YUM to exclude MySQL from updates"
						sed -i "s/exclude=[.]*/& MySQL*/g" $YUM
					fi
					if [ "$JDKEXCLUDED" != "true" ]
					then
						white "  - updating $YUM to exclude JDK from updates"
						sed -i "s/exclude=[.]*/& jdk*/g" $YUM
					fi
				else
					white "  - updating $YUM to exclude automatic MySQL and JDK updates"
					echo "exclude=MySQL* jdk*" >> $YUM
				fi
			else
				warn "This is a RedHat based distribution without YUM installed."
				white
				warn "The file yum.conf cannot be found."
				white
				warn "Exclusion of MySQL and JDK from automatic updates that might break DME"
				warn "is not possible."
				white
				case $DISTRO in
					RHEL4|RHEL5)
						white "If you have bought a license for the distribution and have not "
						white "activated the license yet for automatic security updates etc."
						white "then please take note to add the following line to the yum.conf"
						white "file when you do."
						white
						white "exclude=MySQL* jdk*"
						white
						white "This will keep MySQL and the JDK that DME depends on, not being"
						white "updated to versions that are not supported or are know to cause"
						white "problems with DME."
						white

					;;
				esac
				enterReturn
			fi
		;;
		SUSE10|SUSE11)
			dwhite "Does not use YUM for updates - MySQL is still at risk if dist update/upgrade is done !" ${FUNCNAME} ${LINENO}
		;;
	esac
	if [ -e /var/dme/etc/do_not_touch ] 
	then
		sed -i "s, LSS,,g" /var/dme/etc/do_not_touch 2> /dev/null
		sed -i "s, $,,g" /var/dme/etc/do_not_touch 2> /dev/null
		sed -i "s,[ ]*,,g" /var/dme/etc/do_not_touch 2> /dev/null
	fi
}

remove_logs()
{
	log4bash 0 "remove_logs()" ${FUNCNAME} ${LINENO}
	log4bash 1 "Removing tmp files" ${FUNCNAME} ${LINENO}
	# Remove install script tmp files etc. but not the log files
	rm -rf $TMPDIR/tmp/*
	rm -rf $TMPDIR/scripts/*
	log4bash 0 " - removed $TMPDIR/tmp/*" ${FUNCNAME} ${LINENO}
	log4bash 0 " - removed $TMPDIR/scripts/*" ${FUNCNAME} ${LINENO}
}

setEarFile() {
	if [ "`echo "$b_version" | sed "s,[^0-9],,g"`" -ge "30" ]
	then
		EARFILE="dme-sync.ear"
	else 	
		case $DATABASE in
				mysql)
					EARFILE="dme_nam.ear"
				;;
				mssql)
					EARFILE="dme_nam_mssql.ear"
				;;
		esac
	fi
	#case $b_version in
	#	3.0|3.5|3.6)
	#		EARFILE="dme-sync.ear"
	#	;;
	#	*)
	#		case $DATABASE in
	#			mysql)
	#				EARFILE="dme_nam.ear"
	#			;;
	#			mssql)
	#				EARFILE="dme_nam_mssql.ear"
	#			;;
	#		esac
	#	;;
	#esac
}

rmDownloadLink()
{
	log4bash 0 "Removing download link" $FUNCNAME $LINENO
	wget "http://${installServer}/login.php?username=$USERNAME}&password=${PASSWORD}&removelink=${DWPATH}" -o /dev/null -O $WGETLOG 
}

finished()
{
	log4bash 0 "finished()" ${FUNCNAME} ${LINENO}
	#white "Cleaning up tmp directories and files"
	
	# Moving $RESUME file to /var/dme/etc/ if exists 
	resumeFile

	# Clean out tmp files
	if [ -d /var/dme/etc ] && [ -e $RESUME ]
	then
		mv -f $RESUME /var/dme/etc/`basename $RESUME`
		log4bash 1 "Resume file moved to /var/dme/etc" ${FUNCNAME} ${LINENO}
	else
		log4bash 1 "No resume file created so no changes was made" ${FUNCNAME} ${LINENO}
	fi
	
	# remove logs
	#remove_logs ## DEBUG
	
	# last function to call
	log4bash 1 "Setting file ownership on all files used by DME"
	chown jboss:jboss /usr/local/jboss* -R 2> /dev/null
	chown jboss:jboss /var/dme -R 2> /dev/null
	log4bash 1 "----------------------------------------------------------" ${FUNCNAME} ${LINENO}
	log4bash 1 "Installation script exit status: OK" ${FUNCNAME} ${LINENO}

	if [ "`ls -1 /usr/local/java/bin/java 2> /dev/null`" == "" ]
	then
		rm -f /usr/local/java 2> /dev/null
		ln -s /usr/java/`ls -1 /usr/java/ | grep jdk | sort -r | head -n1` /usr/local/java
	fi

	# Report a clean exit to the kernel
	if [ "$DWLINK" != "" ]
	then
		rmDownloadLink
	fi
	exit 0
}



downloadLocal()
{
	log4bash 0 "downloadLocal($1)" ${FUNCNAME} ${LINENO}
	# If the installation is done from localhost then do not
	# download the software, just copy it from dme-local-install
	# to $TMPDIR/files
	if [ -d $CWD/_files_ ]
	then
		log4bash 0 " - faking download from $installServer" ${FUNCNAME} ${LINENO}
		cp $CWD/_files_/`basename $1` $TMPDIR/files/
	fi
}

downloadExtra() 
{
	if [ -e $CWD/_files_ ]
	then
		log4bash 0 "Not downloading extras for this installation"
		if [ -e $CWD/_files_/`basename $1` ]
		then
			cp $CWD/_files_/`basename $1` $TMPDIR/files/ 2> /dev/null
		fi
		return
	fi
	log4bash 0 "downloadExtra($1)" ${FUNCNAME} ${LINENO}
	# Download a specific file $1
	cd $TMPDIR/files
	rm -f $TMPDIR/files/`basename $1`
	dwhite "        attempting to download '$1'" ${FUNCNAME} ${LINENO}
	downloadFile="$installServer/$DWPATH/${1}"
	wget --timeout 5 -N --progress=dot "$downloadFile" -o $WGETLOG 2> /dev/null
	if [ "`grep "^HTTP" $WGETLOG | grep "40."`" != "" ]
	then
		DOWNLOADERROR="file not downloaded"
		log4bash 0 " - failed to download ${1}" ${FUNCNAME} ${LINENO}
	else
		DOWNLOADERROR=""
	fi
}


download()
{
	#log4bash 0 "download(\"$1\", \"$2\")" ${FUNCNAME} ${LINENO}
	if [ -d $CWD/_files_ ]
	then
		downloadLocal $1 $2 
		return
	else	
		local downPWD=`pwd`
		cd $TMPDIR/files
		# Download a file 
		# If the global variable $installServer is set then that 
		# will act as http://$installServer/$filename where filename can
		# contain extra path information.
	
		# $1 = filename
		# $2 = FQDN for server
	
		# Check if $USERNAME and $PASSWORD have been set
		if [ "$USERNAME" == "" ] || [ "$PASSWORD" == "" ]
		then
			log4bash 0 " - not authenticated for download" ${FUNCNAME} ${LINENO}
			_exit "Authentication problem with download\n  - Please check your HTTP Download credentials (username and/or password)"
		fi
		
		# Check if a filename has been set
		if [ "$1" == "" ]
		then
			_exit "Script error...\n  - Could not download file \"$1\" from server"
		else
			local filename="`echo $1 | sed "s,^\/,,g"`"
		fi
	
		# Check if $installServer is set 
		if [ "$installServer" != "" ]
		then 
			local server=$installServer
		else
			# Check if a server has been provided for parameter $3
			if [ "$2" == "" ]
			then
				log4bash 0 " - internal script error" ${FUNCNAME} ${LINENO}
				_exit "Script error...\n  - No server specified to download from! '$0' '$1' '$2'"
			else
				local server="$2"
			fi
		fi
	
		# Set download server type (default is http://)
		if [ "`echo "$server" | grep "^http://\|^ftp://"`" == "" ]
		then
			# Adding "http://" to the $server variable
			server="http://`echo $server | sed "s,http://,,g"`"
		fi
	
		#local downloadFile="$server/$filename"
		local downloadFile="$server/$DWPATH/$filename"
	
		# Do the actual download
		#echo "wget -nc --progress=dot --http-user=$USERNAME --http-passwd=$PASSWORD $downloadFile -o $WGETLOG"

		tmpbasename=`basename $downloadFile`
		if [ -e "$TMPDIR/files/$tmpbasename" ] && [ "$tmpbasename" != "test" ]
		then
			DOWNLOADFILE=true
			#MD5="`md5sum $TMPDIR/files/$tmpbasename | cut -d" " -f1`  $filename"
			MD5="`grep "$(md5sum $TMPDIR/files/$tmpbasename 2> /dev/null)" $TMPDIR/files/md5sum.txt 2> /dev/null`"
			if [ "$MD5" == "" ]
			then
				#dwhite "  File id: $tmpbasename ($filename)"
				#dwhite "  MD5sum : `grep "$filename" $TMPDIR/files/md5sum.txt | cut -d" " -f1`"
				#dwhite "  Files MD5sum did not match checksum file"
				#dwhite "  Removing file and downloading again"
				rm -f $TMPDIR/files/$tmpbasename 2> /dev/null
			fi
			if [ "$OUTPUTFILENAME" != "" ]
			then
				filename=$OUTPUTFILENAME
				OUTPUTFILENAME="-O $OUTPUTFILENAME"
			fi
			dwhite "  Downloading $filename " ${FUNCNAME} ${LINENO}
			wget -N --progress=dot "${downloadFile}" -o $WGETLOG.$tmpbasename $OUTPUTFILENAME 2> /dev/null 
			unset OUTPUTFILENAME
			checkDownload $filename
			
			#if [ "`grep $MD5 $TMPDIR/files/test 2> /dev/null | grep "$filename"`" == "" ] && [ "`echo $downloadFile | grep "linux/scripts"`" == "" ]
			#then
			#	dwhite " File is = $tmpbasename"
			#	dwhite " MD5sum  = $MD5"
			#	if [ "`grep "${filename}$" $TMPDIR/files/test 2> /dev/null`" != "" ]
			#	then
			#		dwhite " MD5 should be: `grep "${filename}$" $TMPDIR/files/test`"
			#	else
			#		dwhite " No MD5 found for the file"
			#	fi
			#	dwhite " MD5 not ok, downloading, please wait..." ${FUNCNAME} ${LINENO}
			#	rm -f $TMPDIR/files/$tmpbasename 2> /dev/null
			#	#wget -nc --progress=dot --http-user=$USERNAME --http-passwd=$PASSWORD "${downloadFile}" -o $WGETLOG 2> /dev/null
			#	if [ "$OUTPUTFILENAME" != "" ]
			#	then
			#		filename=$OUTPUTFILENAME
			#		OUTPUTFILENAME="-O $OUTPUTFILENAME"
			#	fi
			#	wget -N --progress=dot "${downloadFile}" -o $WGETLOG.$tmpbasename $OUTPUTFILENAME 2> /dev/null 
			#	unset OUTPUTFILENAME
			#
			#	checkDownload $filename
			#fi	
		else
			#log4bash 1 "Downloading $tmpbasename " ${FUNCNAME} ${LINENO}
			#dwhite "  File $tmpbasename not found in $TMPDIR/files/"
			dwhite "  Downloading $filename " ${FUNCNAME} ${LINENO}
			#wget -nc --progress=dot --http-user=$USERNAME --http-passwd=$PASSWORD "${downloadFile}" -o $WGETLOG 2> /dev/null
			if [ "$OUTPUTFILENAME" != "" ]
			then
				filename=$OUTPUTFILENAME
				OUTPUTFILENAME="-O $OUTPUTFILENAME"
			fi
			wget -N --progress=dot "${downloadFile}" -o $WGETLOG.$tmpbasename $OUTPUTFILENAME 2> /dev/null 
			unset OUTPUTFILENAME

			if [ ! -e `basename $filename` ] && [ "`basename $filename`" != "test" ]
			then
				if [ "`basename $filename`" != "test" ]
				then
					_exit "Error downloading file \"$downloadFile\"\n  - 'wget' exited with error code $?\n  - Please check that wget works properly"
				else
					_exit "Could not connect to download server (http://$installServer)"
				fi
			fi
			checkDownload $filename
		fi

		if [ "`file $filename | grep "CRLF\|terminators"`" != "" ]
		then
			dwhite "Text file is in DOS format. Converting to unix format" ${FUNCNAME} ${LINENO}
			cat $filename | sed "s,,\n,g" > $filename.unix
			mv $filename $filename.dos
			mv $filename.unix $filename
			rm -f $filename.dos
		fi
		
		unset downloadFile server filename path
		cd $downPWD
	fi
}

checkUsernameAndPassword()
{
	# Check the username and password the user has provided
	rm -f $WGETLOG
	downloadFile="http://${installServer}/login.php?username=${USERNAME}&password=${PASSWORD}"
	#downloadFile="'${downloadFile}'"
	#warn $downloadFile
	rm -f $TMPDIR/tmp/.login 2> /dev/null
	dwhite "Checking username and password" ${FUNCNAME} ${LINENO}
	wget "${downloadFile}" -O $TMPDIR/tmp/.login -o $WGETLOG 2> /dev/null
	if [ "`cat $TMPDIR/tmp/.login | grep "^download"`" != "" ]
	then
		dwhite "  - username and password authenticated" ${FUNCNAME} ${LINENO}
		DWPATH=`cat $TMPDIR/tmp/.login`
		log4bash 0 "DWPATH: $DWPATH" $FUNCNAME $LINENO
		rm -f $TMPDIR/tmp/.login
	else
		warn "An error occured:"
		cat $TMPDIR/tmp/.login 2> /dev/null
		white
		white
		rm -f $TMPDIR/tmp/.login 2> /dev/null
		exit
	fi	
}
getUsernameAndPassword()
{
	log4bash 0 "getUsernameAndPassword()" ${FUNCNAME} ${LINENO}
	if [ "`ls -1 /tmp/.tmp_1932 2> /dev/null`" != "" ]
	then
		USERNAME="`cat /tmp/.tmp_1932 | grep ^USERNAME= | cut -d"=" -f2`"
		PASSWORD="`cat /tmp/.tmp_1932 | grep ^USERNAME= | cut -d"=" -f2`"
		CONTINUE="true"
		rm -f /tmp/.tmp_1932
		enterReturn
		return
		enterReturn
	fi

	log4bash 1 "Checking for HTTP username and password" ${FUNCNAME} ${LINENO}
	# Check for ARGV parameters that we can use

	local HELP="false"
	if [ "${argv[0]}" == "-u" ] || [ "${argv[0]}" == "--username" ] && 
		[ "${argv[1]}" != "-p" ] && [ "${argv[1]}" != "--password" ] && 
		[ "${argv[1]}" != "" ]
	then
		USERNAME=${argv[1]}
		good "Username provided via CLI"
	fi
	if [ "${argv[2]}" == "-p" ] || [ "${argv[2]}" == "--password" ] && [ "$USERNAME" != "" ] && [ "${argv[3]}" != "" ]; then
		PASSWORD=${argv[3]}
		warn "Password provided via CLI (remember to clear your .bash_history file)"
	fi
	
	if [ "$USERNAME" == "false" ] && [ "$PASSWORD" == "false" ]
	then 
		white "Please fill in the following information"; 
	fi
	if [ "$USERNAME" == "false" ]
	then 
		goodn "Enter username: "; echo -n -e $GOOD; read USERNAME; echo -n -e $NORMAL; 
	
	else 	if [ "$PASSWORD" == "false" ]
		then 
			white " * Username set to: $USERNAME"; 
			log4bash 1 " - username set via CLI" ${FUNCNAME} ${LINENO}
		fi
	fi
	if [ "$USERNAME" == "" ]
	then 	
		_exit "You need to enter a username"
	else
		log4bash 1 " - username provided interactivly"  ${FUNCNAME} ${LINENO}
	fi
	
	if [ "$PASSWORD" == "false" ]
	then goodn "Enter download password: "; 
		read -s PASSWORD; 
		normal
	fi
	if [ "$PASSWORD" == "" ]
	then 
		_exit "You need to enter a password for the user \"$USERNAME\" to download and install"; 
	else
		log4bash 1 " - password provided interactivly" ${FUNCNAME} ${LINENO}
	fi

	checkUsernameAndPassword
}

decryptPassword() {
	if [ "`grep "security-domain" $dmeIbase/etc/jboss/dmebaseDB-ds.xml`" == "" ]
	then
		dbUser=`grep user $dmeIbase/etc/jboss/dmebaseDB-ds.xml | cut -d">" -f2 | cut -d"<" -f1`
		dbPassword="`grep password $dmeIbase/etc/jboss/dmebaseDB-ds.xml | cut -d">" -f2 | cut -d"<" -f1`"
		dwhite "DB USERNAME: $dbUser"
		dwhite "DB PASSWORD: $dbPassword"
		return
	fi 
	EncryptDecryptPassword="EncryptDecryptPassword"
	EncryptDecryptPasswordCode="/*
 * JBoss.java - Blowfish encryption/decryption tool with JBoss default password
 *    Daniel Martin Gomez <daniel@ngssoftware.com> - 03/Sep/2009
 *
 * This file may be used under the terms of the GNU General Public License 
 * version 2.0 as published by the Free Software Foundation:
 *   http://www.gnu.org/licenses/gpl-2.0.html
 */
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;

import java.math.BigInteger;

public class $EncryptDecryptPassword 
{

  public static void main(String[] args) throws Exception
  {

    if ( ( args.length != 2 ) || !( args[0].equals(\"-e\") || args[0].equals(\"-d\") ) )
    {
      System.out.println( \"Usage: java JBoss <-e|-d> <encrypted_password>\" );
      return;
    }
    
    String mode = args[0];

    byte[] kbytes = \"jaas is the way\".getBytes(); 
    SecretKeySpec key = new SecretKeySpec(kbytes, \"Blowfish\"); 
    Cipher cipher = Cipher.getInstance(\"Blowfish\"); 

    String out = null;

    if ( mode.equals(\"-e\") )
    {
      String secret = args[1];
      cipher.init(Cipher.ENCRYPT_MODE, key); 
      byte[] encoding = cipher.doFinal(secret.getBytes()); 
      out = new BigInteger(encoding).toString(16); 
    } 
    else
    {
      BigInteger secret = new BigInteger(args[1], 16);
      cipher.init(Cipher.DECRYPT_MODE, key);
      byte[] encoding = cipher.doFinal(secret.toByteArray()); 
      out = new String(encoding);
    }
    System.out.println( out );
  }
}"
	dwhite " - please wait while updating database"
	cd $TMPDIR/tmp/
	rm -f $EncryptDecryptPassword.*	
	echo "$EncryptDecryptPasswordCode" > $TMPDIR/tmp/$EncryptDecryptPassword.java
	cd $TMPDIR/tmp/
	/usr/local/java/bin/javac $EncryptDecryptPassword.java #1> /dev/null 2> /dev/null
	RETVAL=$?
	encUsername=`grep -A10 "EncryptDBPassword" $dmeIbase/conf/login-config.xml | grep username | cut -d">" -f2 | cut -d"<" -f1`
	encPassword=`grep -A10 "EncryptDBPassword" $dmeIbase/conf/login-config.xml | grep password | cut -d">" -f2 | cut -d"<" -f1`
	dbUser="$encUsername"
	dbPassword="`cd $TMPDIR/tmp/ ; /usr/local/java/bin/java $EncryptDecryptPassword -d "$encPassword"`"
	#dwhite "Decrypted username: $dbUser"
	#dwhite "Encrypted password: $encPassword"
	#dwhite "Decrypted password: $dbPassword"
	cd $TMPDIR/tmp/
	rm -f $EncryptDecryptPassword.*
	dbHost=`grep "connection-url" $dmeIbase/etc/jboss/dmebaseDB-ds.xml | cut -d/ -f3 | cut -d: -f1`
	dbName=`grep "connection-url" $dmeIbase/etc/jboss/dmebaseDB-ds.xml | cut -d/ -f4 | cut -d"?" -f1`
  	if [ "`echo $dbName | grep ":"`" != "" ]
	then
		dbName=`grep "connection-url" $dmeIbase/etc/jboss/dmebaseDB-ds.xml | cut -d/ -f4 | cut -d"?" -f1 | cut -d: -f1`
		dbPort=`grep "connection-url" $dmeIbase/etc/jboss/dmebaseDB-ds.xml | cut -d/ -f3 | cut -d: -f2`
	else
		dbPort=""
	fi
			
}

getCIDR()
{
	log4bash 0 "getCIDR($1)" ${FUNCNAME} ${LINENO}
	# Set the CIDR variable to the "IP Prefix" for the 
	# given netmask for an interface
	case $1 in 
		255.255.255.252)	CIDR=30;;
		255.255.255.248)	CIDR=29;;
		255.255.255.240)	CIDR=28;;
		255.255.255.224)	CIDR=27;;
		255.255.255.192)	CIDR=26;;
		255.255.255.128)	CIDR=25;;
		255.255.255.0) 		CIDR=24;;
		255.255.254.0) 		CIDR=23;;
		255.255.252.0) 		CIDR=22;;
		255.255.248.0) 		CIDR=21;;
		255.255.240.0) 		CIDR=20;;
		255.255.224.0) 		CIDR=19;;
		255.255.192.0) 		CIDR=18;;
		255.255.128.0) 		CIDR=17;;
		255.255.0.0) 		CIDR=16;;
		255.254.0.0) 		CIDR=15;;
		255.252.0.0) 		CIDR=14;;
		255.248.0.0) 		CIDR=13;;
		255.240.0.0) 		CIDR=12;;
	esac
	for x in $(seq 12 30)
	do
		if [ "$1" == "$x" ]
		then
			CIDR=$1
		fi
	done
}
getNetmask()
{
	log4bash 0 "getNetmask($1)" ${FUNCNAME} ${LINENO}
	case $1 in 
		1) NETMASK="128.0.0.0";;
		2) NETMASK="192.0.0.0";;
		3) NETMASK="224.0.0.0";;
		4) NETMASK="240.0.0.0";;
		5) NETMASK="248.0.0.0";;
		6) NETMASK="252.0.0.0";;
		7) NETMASK="254.0.0.0";;
		8) NETMASK="255.0.0.0";;
		9) NETMASK="255.128.0.0";;
		10) NETMASK="255.192.0.0";;
		11) NETMASK="255.224.0.0";;
		12) NETMASK="255.240.0.0";;
		13) NETMASK="255.248.0.0";;
		14) NETMASK="255.252.0.0";;
		15) NETMASK="255.254.0.0";;
		16) NETMASK="255.255.0.0";;
		17) NETMASK="255.255.128.0";;
		18) NETMASK="255.255.192.0";;
		19) NETMASK="255.255.224.0";;
		20) NETMASK="255.255.240.0";;
		21) NETMASK="255.255.248.0";;
		22) NETMASK="255.255.252.0";;
		23) NETMASK="255.255.254.0";;
		24) NETMASK="255.255.255.0";;
		25) NETMASK="255.255.255.128";;
		26) NETMASK="255.255.255.192";;
		27) NETMASK="255.255.255.224";;
		28) NETMASK="255.255.255.240";;
		29) NETMASK="255.255.255.248";;
		30) NETMASK="255.255.255.252";;
		*) warn "The netmask \"$1\"is not supported!"; NETMASK="" ;;
	esac
	dwhite "CIDR $1 converted to $NETMASK" ${FUNCNAME} ${LINENO}
}

getBroadcast()
{
	log4bash 0 "getBroadcast($1, $2)" ${FUNCNAME} ${LINENO}
	local ip=$1
	local netmask=$2

	ip1=`echo $ip | cut -d. -f1`
	ip2=`echo $ip | cut -d. -f2`
	ip3=`echo $ip | cut -d. -f3`
	ip4=`echo $ip | cut -d. -f4`

	getCIDR $netmask
	netmask=$CIDR

	case $CIDR in 
		30)     BROADCAST=$ip1.$ip2.$ip3.`expr  $ip4 + (8-($ip4%8))`;;
		24)	BROADCAST=$ip1.$ip2.$ip3.255;;
		16)	BROADCAST=$ip1.$ip2.255.255;;
	esac
}
ipCheck()
{
	log4bash 0 "ipCheck()" ${FUNCNAME} ${LINENO}
	log4bash 1 "Checking for INET address... " ${FUNCNAME} ${LINENO}
	case $DISTRO in
		RHEL4|RHEL5|FC5|FC7|FC8|FC9|FC10|SUSE10|SUSE11|CENTOS5)
			# Active interface
			unset tmp
			declare -a tmp
			tmp=( `cat /proc/net/dev | grep -v "Inter\|face\|lo" | sed "s/^ *//g" | sed "s/  */:/g" | sed "s/::/:/g" | cut -d: -f1` )
			if [ "${#tmp[@]}" -gt 1 ]
			then
				# If several connected interfaces were found then check which is used
				# if more than one is used then ask the user
				for x in ${tmp[@]}
				do
					whiten " - interface $x is "
					temp=`cat /proc/net/dev | grep -v "Inter\|face\|lo" | sed "s/^ *//g" | sed "s/  */:/g" | sed "s/::/:/g" | grep "^$x" | cut -d: -f2`
					if [ "$temp" == "0" ]
					then
						white "not active"
						tmp=( ${tmp[@]//$x/} )
					else
						white "active"
					fi
				done
			fi
			if [ "${#tmp[@]}" -gt "1" ] && [ ! -d /var/dme/instances/base ]
			then
				log4bash 1 "  - more than one interface found" ${FUNCNAME} ${LINENO}
				white
				warn  "Found more than one active interface. "
				white "Please choose which is the primary (Internet) where the"
				white "server will accept connections. This interface will be the "
				white "default interface that the DME \"base\" instance will"
				white "bind to. If you are about to install additinal instances"
				white "then you will be asked later which interface you want"
				white "to bind the instance to."
				max=`expr ${#tmp[@]} - 1`
				while (true)
				do
					index=0
					white
					for x in ${tmp[@]}
					do
						white "    $index) $x `ip a s dev $x | grep "inet " | sed "s, [ ]*, ,g" | cut -d" " -f3 | head -n1`"
						((index+=1))
					done

					white
					whiten "Choose interface 0 to ${max} [default => 0]: " 
					unset REPLY
					read 
					if [ "$REPLY" == "" ]
					then
						REPLY="0"
					fi
					if [ "$REPLY" -gt -1 ] && [ "$REPLY" -lt "${#tmp[@]}" ]
					then
						ip_interface=${tmp[$REPLY]}
						log4bash 1 "  - DME interface is $ip_interface" ${FUNCNAME} ${LINENO}
						break
					else
						warn "$REPLY is not a valid choice"
					fi
				done

			else
				# Found only one active interface
				ip_interface=${tmp}
				log4bash 1 "  - DME interface is $ip_interface" ${FUNCNAME} ${LINENO}
			fi

			ip_inet=`ip a s | grep  "$ip_interface$" | grep "inet " | tail -n 1 | sed "s/^ *//g" | cut -d" " -f2 | cut -d/ -f1`
			getNetmask `ip a s | grep  "$ip_interface$" | grep "inet " | tail -n 1 | sed "s/^ *//g" | cut -d" " -f2 | cut -d/ -f2`
			ip_sub=$NETMASK
			ip_bdr=`ip a s | grep  "$ip_interface$" | grep "inet " | tail -n 1 | sed "s/^ *//g" | cut -d" " -f4` 
		;;
		*)
			# Check for a non localhost IP address
			dwhite "Distribution is not fully supported - alternative IP check in use" ${FUNCNAME} ${LINENO}
			ip_inet=`/sbin/ip addr |grep inet | grep -v " 127" | cut -d"/" -f 1 | egrep -m1 -o '[0-9]+.[0-9]+.[0-9]+.[0-9]+'`
			if [ "$ip_inet" == "" ];
			then	
				ewarn "Could not find an IP address with /sbin/ip... trying /sbin/ifconfig"
			fi
				ip_inet=`/sbin/ifconfig | grep inet | grep -v 127 | cut -d: -f 2 | egrep -m1 -o '[0-9]+.[0-9]+.[0-9]+.[0-9]+'`
				if [ "$ip_inet" == "" ]
			then
				ewarn "Could not find an IP address with /sbin/ifconfig\n  - Make sure the network is up and running"
				_exit "No IP address configured on the machine\n  - Make sure the network is configured correctly\n  - Make sure that the machine can connect to the Internet"
			fi
			if [ "`ip a s | grep "^[0-9]" | grep -v ": lo" | grep BROADCAST | wc -l`" == "1" ]
			then
				tmpNIC=`ip a s | grep "^[0-9]" | grep -v ": lo" | grep BROADCAST | cut -d" " -f2 | sed "s,:,,g"`
			else
				dwhite "  - found more than one interface" ${FUNCNAME} ${LINENO}
				tmpNIC=`ip a s | grep "^[0-9]" | grep -v ": lo" | grep BROADCAST | head -n1 | cut -d" " -f2 | sed "s,:,,g"`
				dwhite "  - choose $tmpNIC" ${FUNCNAME} ${LINENO}
			fi
			ip_sub=`/sbin/ifconfig $tmpNIC | grep $ip_inet | egrep -m2 -o '[0-9]+.[0-9]+.[0-9]+.[0-9]+' | grep -v $ip_inet | tr '\n' ' ' | cut -d" " -f2`
			ip_bdr=`/sbin/ifconfig $tmpNIC | grep $ip_inet | egrep -m2 -o '[0-9]+.[0-9]+.[0-9]+.[0-9]+' | grep -v "^$ip_inet$" | grep -v "$ip_sub"`
			ip_interface=$tmpNIC
		;;
	esac
	
	# Setup ip sub var for easy comparing
	inet1=`echo $ip_inet | cut -d. -f1`
	inet2=`echo $ip_inet | cut -d. -f2`
	inet3=`echo $ip_inet | cut -d. -f3`
	inet4=`echo $ip_inet | cut -d. -f4`
	ip_network="$inet1.$inet2.$inet3.0" # Do better setup
	
	# Setup some variables for easy IPTables setup later
	netmask1=`echo "$ip_sub" | cut -d. -f1`
	netmask2=`echo "$ip_sub" | cut -d. -f2`
	netmask3=`echo "$ip_sub" | cut -d. -f3`
	netmask4=`echo "$ip_sub" | cut -d. -f4`
	
	# Class-C 255.255.255.xxx
	if [ "$netmask1.$netmask2.$netmask3" == "255.255.255" ]
	then
		network_type="class-C"
		case $netmask4 in 
			0)	ip_net=24; ip_addresses=256; ip_hosts=254;;
			128)	ip_net=25; ip_addresses=128; ip_hosts=126;;
			192)	ip_net=26; ip_addresses=64; ip_hosts=62;;
			224)	ip_net=27; ip_addresses=32; ip_hosts=30;;
			240)	ip_net=28; ip_addresses=16; ip_hosts=14;;
			248)	ip_net=29; ip_addresses=8; ip_hosts=6;;
			252)	ip_net=30; ip_addresses=4; ip_hosts=2;;
			255)	ip_net=32; ip_addresses=1; ip_hosts=1;;
			*)	ip_net='unknown class-C network'; ip_hosts=0; ip_addresses=0;;
		esac
	fi
	# Class-B 255.255.xxx.0
	if [ "$netmask1.$netmask2.$netmask4" == "255.255.0" ]
	then
		network_type="class-B"
		case $netmask3 in
			254)	ip_net=23; ip_addresses=512; ip_hosts=510;;
			252)	ip_net=22; ip_addresses=1024; ip_hosts=1022;;
			248)	ip_net=21; ip_addresses=2048; ip_hosts=2046;;
			240)	ip_net=20; ip_addresses=4096; ip_hosts=4094;;
			224)	ip_net=19; ip_addresses=8192; ip_hosts=8190;;
			192)	ip_net=18; ip_addresses=16384; ip_hosts=16382;;
			128)	ip_net=17; ip_addresses=32768; ip_hosts=32766;;
		esac
	fi
	# Class-A 255.xxx.0.0
	if [ "$netmask1.$netmask3.$netmask4" == "255.0.0" ]
	then
		network_type="class-A"
		case $netmask2 in
			128)	ip_net=9;  ip_addresses=8388608; ip_hosts=8388606;;
			192)	ip_net=10; ip_addresses=4194304; ip_hosts=4194302;;
			224)	ip_net=11; ip_addresses=2097152; ip_hosts=2097150;;
			240)	ip_net=12; ip_addresses=1048576; ip_hosts=1048574;;
			248)	ip_net=13; ip_addresses=524288; ip_hosts=524286;;
			252)	ip_net=14; ip_addresses=262144; ip_hosts=262142;;
			254)	ip_net=15; ip_addresses=131072; ip_hosts=131070;;
			255)	ip_net=16; ip_addresses=65536; ip_hosts=65534;;
			*)	ip_net='unknown class-A network'; ip_hosts=0; ip_addresses=0;;
		esac
	fi
	if [ "$ip_inet" == "not a class-A network" ]
	then
		network_type=""
		case $netmask1 in
			240)	ip_net=4; ip_addresses=268435454; ip_hosts=268435456;;
			248)	ip_net=5; ip_addresses=134217728; ip_hosts=134217726;;
			252)	ip_net=6; ip_addresses=67108864; ip_hosts=67108862;;
			254)	ip_net=7; ip_addresses=33554432; ip_hosts=33554430;;
			255)	ip_net=8; ip_addresses=16777216; ip_hosts=16777214;;
			*)	ip_net='unknown network'; ip_hosts=0; ip_addresses=0;;
		esac
	fi
	# output for the user
	#good "System IP information:"; echo -n " INET addr: "; goodn "$ip_inet, "; echo -n "Netmask: "; good $ip_sub
	
	#if [ "$inet1" != "127" ] && [ "$inet2" != "0" ] && [ "$inet3" != "0" ] && [ "$inet4" != "1" ]
	# Former check to hard - will not install on clas-B networks
	if [ "$inet1" != "127" ]
	then
		
		# Find the gateway	
		route=`route -n | grep "^$inet1.$inet2.$inet3.0" | sed "s/^................//g" | cut -d" " -f1`
		gw=`route -n | grep "^$route" | sed "s/^................//g" | cut -d" " -f1 | grep -v "0.0.0.0"`
		white "IP Information for $ip_interface:"
		whiten "    IP address   : "; normal $ip_inet
		whiten "    Subnet       : "; normal $ip_sub
		whiten "    Network      : "; normal $ip_network
		whiten "    Broadcast    : "; normal $ip_bdr
		whiten "    Gateway      : "; normal $gw
		whiten "That makes this a "
		normaln "$ip_net "; whiten "bit "
		normaln "$network_type "; whiten "network with a total of "; normaln $ip_addresses; whiten " ip-address(es) "
		whiten "for "; normaln $ip_hosts; white " host(s)"
		
		log4bash 1 "IP Information:" ${FUNCNAME} ${LINENO}
		LOGINFO="false"	# Make log information play nice
		log4bash 1 "    IP address   : "; log4bash 1 $ip_inet ${FUNCNAME} ${LINENO}
		log4bash 1 "    Subnet       : "; log4bash 1 $ip_sub ${FUNCNAME} ${LINENO}
		log4bash 1 "    Network      : "; log4bash 1 $ip_network ${FUNCNAME} ${LINENO}
		log4bash 1 "    Broadcast    : "; log4bash 1 $ip_bdr ${FUNCNAME} ${LINENO}
		log4bash 1 "    Gateway      : "; log4bash 1 $gw ${FUNCNAME} ${LINENO}
		log4bash 1 "    (" ${FUNCNAME} ${LINENO}
		log4bash 1 "$ip_net "; log4bash 1 "bit " ${FUNCNAME} ${LINENO}
		log4bash 1 "$network_type "; log4bash 1 "network with a total of "; log4bash 1 $ip_addresses; log4bash 1 " ip-addresses " ${FUNCNAME} ${LINENO}
		log4bash 1 "for "; log4bash 1 $ip_hosts; log4bash 1 " hosts)" ${FUNCNAME} ${LINENO}
		LOGINFO="true" # Set log information to normal [INFO] `date`	
	
	else
		E_NETWORK="true" # Enable the network error message
		_exit "did find an INET address, but not sure if it's good"
	fi

}
checkIPAddress() 
{
	log4bash 0 "checkIPAddress($1)" ${FUNCNAME} ${LINENO}
	# This function checks $1 if it is a valid IP address or IP network address
	# If true the variable VALIDIP is set to true otherwise to false.

	# Default to false IP address or network
	VALIDIP="false"

	# Check if there we received a variable to work on
	if [ "$1" == "" ]
	then
		warn "ERROR: Cannot check an non existing IP address (NULL)"
		return
	fi

	# Setup ip sub var for easy comparing
	if [ "`echo $1 | sed "s,\.,&\n,g" | wc -l `" != "4" ]
	then
		warn "IP address $1 is not a valid IPv4 IP address"
		sleep 2
		return
	fi
	if [ "`echo $1 | sed "s,\.,,g" | grep "[^0-9]"`" != "" ]
	then
		warn "IP address expectd !!!"
		sleep 2
		return
	fi
	i1=`echo $1 | cut -d"." -f1 | sed "s,\.,,g"`
	i2=`echo $1 | cut -d"." -f2 | sed "s,\.,,g"`
	i3=`echo $1 | cut -d"." -f3 | sed "s,\.,,g"`
	i4=`echo $1 | cut -d"." -f4 | sed "s,\.,,g"`
	dwhite "  - checking IP address: $i1 $i2 $i3 $i4" ${FUNCNAME} ${LINENO}
	# Check firxt octet
	if [ "$i1" != "" ]
	then
		dwhite "  - checking $i1 > 0 && $i1 < 256"  ${FUNCNAME} ${LINENO}
		if [ "$i1" -gt "0" ] && [ "$i1" -lt "256" ]
		then
			dwhite "  - first octet is OK" ${FUNCNAME} ${LINENO}
			VALIDIP="true"
		else
			warn "First octet of IP $1 is invalid"
			return
		fi
	else
		warn "First octet of IP $1 is invalid"
		return
	fi

	# Check second octet
	if [ "$i2" != "" ]
	then
		dwhite "  - checking $i2 >= 0 && $i2 <= 255"  ${FUNCNAME} ${LINENO}
		if [ "$i2" -ge "0" ] && [ "$i2" -le "255" ]
		then
			dwhite "  - second octet is OK" ${FUNCNAME} ${LINENO}
			VALIDIP="true"
		else
			warn "Second octet of IP $1 is invalid"
			return
		fi
	else
		warn "Second octet of IP $1 is invalid"
		return
	fi

	# Check third octet
	if [ "$i3" != "" ]
	then
		dwhite "  - checking $i3 >= 0 && $i3 <= 255"  ${FUNCNAME} ${LINENO}
		if [ "$i3" -ge "0" ] && [ "$i3" -le "255" ]
		then
			dwhite "  - third octet is OK" ${FUNCNAME} ${LINENO}
			VALIDIP="true"
		else
			warn "Third octet of IP $1 is invalid"
			return
		fi
	else
		warn "Third octet of IP $1 is invalid"
		return
	fi

	# Check forth octet
	if [ "$i4" != "" ]
	then
		dwhite "  - checking $i4 >= 0 && $i4 <= 255"  ${FUNCNAME} ${LINENO}
		if [ "$i4" -ge "0" ] && [ "$i4" -le "255" ]
		then
			dwhite "  - forth octet is OK" ${FUNCNAME} ${LINENO}
			VALIDIP="true"
		else
			warn "Fourth octet of IP $1 is invalid"
			return
		fi
	else
		warn "Fourth octet of IP $1 is invalid"
		return
	fi

	if [ "$i4" == "0" ]
	then
		dwhite "  - IP address $1 is a network" ${FUNCNAME} ${LINENO}
	fi

	if [ "$i4" == "255" ]
	then
		dwhite "  - IP address $1 is a broadcast address" ${FUNCNAME} ${LINENO}
	fi
}

dnsCheck()
{
	log4bash 0 "dnsCheck()" ${FUNCNAME} ${LINENO}
	whiten "Checking DNS to $installServer... "
	log4bash 1 "Checking DNS to $installServer... " ${FUNCNAME} ${LINENO}
	# Check if the DNS is setup correctly
	
	## DEBUG - remove if-fi
	if [ "$TESTINSTALL" == "true" ]
	then
		tmpDNSServers=`cat /etc/resolv.conf | grep -i nameserver | wc -l`
		if [ "$tmpDNSServers" -gt 0 ]
		then
			white "  - DNS configured in /etc/resolv.conf"
			cat /etc/resolv.conf | grep -i nameserver | sed "s,nameserver,    &,g"
		else
			warn  "  - no DNS entries found in /etc/resolv.conf"
			warn  "    missing 'nameserver x.x.x.x' declerations"
			if [ "`echo $installServer | egrep -m1 "[0-9]*?\.[0-9]*?\.[0-9]*?\.[0-9]*"`" == "" ]
			then
				_exit "DME download server cannot be reached"
			else
				warn "DME installation will continue without DNS setup."
				warn "DME will fail to start and configure correctly without DNS"
				warn "DME will not start automaticly after install."
				log4bash 1 "  - setting NOSTART to true" ${FUNCNAME} ${LINENO}
				NOSTART="true"
			fi
		fi
	fi
}

checkServer()
{
	log4bash 0 "checkServer()" ${FUNCNAME} ${LINENO}


	# Check the avaliable space on filesystem
	#if [ "`df -l /var | tail -n1 | cut -b-5`" == "" ]
	#then
	#	ROOT=`df -l /var | tail -n1 | sed "s, [ ]*, ,g" | cut -d" " -f3`
	#else	
	#	ROOT=`df -l /var | tail -n1 | sed "s, [ ]*, ,g" | cut -d" " -f4`
	#fi
	ROOT=`df -h /var | sed "s, [ ]*, ,g" | tail -n1 | tr ' ' '\n' | tail -n3 | head -n1 | sed "s,\,,.,g" | cut -d"." -f1`
	white "Diskspace found on /var partition: ${ROOT}"
	ROOT=`df -h /var | sed "s, [ ]*, ,g" | tail -n1 | tr ' ' '\n' | tail -n3 | head -n1 | sed "s,[a-zA-Z]*,,g" | sed "s,\,,.,g" | cut -d"." -f1`
	if [ "$ROOT" -le "20" ]
	then
		if [ "$MINDISKSIZE" -lt "5" ]
		then
			MINDISKSIZE=5
		fi
		# Minumum disk size needed for a DME install/upgrade
		if [ "$ROOT" -lt "$MINDISKSIZE" ]
		then
			while (true) 
			do
				topScreen "Not enough diskspace"
				#white "Found ${ROOT}GB of available diskspace."
				#white
				#white "Minimum required for installation is: ${MINDISKSIZE}GB"
				#white 
				#white "Please read the documentation for required diskspace for DME"
				#white
				#white "Please clean up the filesystem or create a new partition"
				#white "mounted under /var with the recommended diskspace available."
				#white
				#whiten "Press "; normaln "Ctrl-C" ; whiten " or "; normaln "quit"; white " to exit the installer to make room for DME"
				#white "without making any changes."
				#white
				#whiten "To continue with the install script write '"; normaln "continue"; white "'"
				#white
				#whiten "Please write your answer: "
				normal "Warning : Only ${ROOT}GB of available diskspace!"
				white ""
				white "${MINDISKSIZE}GB is recommended for installation."
				white ""
				whiten "Type '"; normaln "ignore"; white "' to disregard this warning (not recomended!)"
				whiten "Type '"; normaln "quit"; white "' to exit the installer to make room for DME "
				white "without making any changes (recomended!)."
				white ""
				whiten "Your choice: "
				unset REPLY
				if [ "$DEFAULTANSWER" != "true" ]
				then
					read
					REPLY="`echo "$REPLY" | tr '[:upper:]' '[:lower:]'`"
				else
					white "ignore"
					REPLY="ignore"
				fi
				if [ "$REPLY" != "ignore" ]
				then
					if [ "$REPLY" == "quit" ]
					then
						white 
						white "Exiting the installer without making any changes."
						white
						exit 0
					else
						warn "You wrote '$REPLY' which is not 'continue', please try again."
						sleep 2
					fi
				else
					dwhite " - user choose to continue with low diskspace"
					break
				fi 
			done
			
		fi
	else
		if [ "$ROOT" -lt "70" ] && [ "$ROOT" -le "$MINDISKSIZE" ]
		then
			topScreen "Diskspace information"
			normal "Less than optimal diskspace found"
			white  "================================="
			white
			white "Currently available diskspace: ${ROOT}GB"
			white
			white "The installation is done on a harddrive/partition with "
			white "less than the optimal 70GB of minimum availiable diskspace."
			white
			white "This is an informational message and the installation will "
			white "continue."
			white
			enterContinue "To continue, press <Enter> "
		fi
	fi
	dwhite "  - diskspace availiable on /var: $ROOT"
	# Check to see if we can log in to the server and download from it
	
	if [ -e "./test" ]; then 	
		log4bash 1 "Removing 'test' file from previous run" ${FUNCNAME} ${LINENO}
		rm -f "./test" 2> /dev/null 
	fi

	#W=`wget -nc --progress=dot --chttp-user=$USERNAME --http-passwd=$PASSWORD http://$installServer/test -o $WGETLOG`

	download "install/dme-install.sh"
	dwhite "  - getting $TMPDIR/files/dme-install.sh version number"
	up2dateVersion="`head -n10 $TMPDIR/files/dme-install.sh | grep Version: | cut -d: -f2 | sed "s,^ [ ]*,,g"`"
	if [ "$up2dateVersion" != "$VERSION" ]
	then
		topScreen "Please download newer installer"
		white
		whiten "The installer you are currently running is version "; normal "$VERSION"
		white 
		whiten "Installer version "; normaln "$up2dateVersion "; white "is currently the only available version"
		white
		white "Please download with the following command and re-run this script:"
		white
		white "wget -N http://install.excitor.dk/install/dme-install.sh"
		white
		exit 0
	fi
	
	
	if [ -f "test" ]; then 	log4bash 1 "Removing 'test' file from test fetch" ${FUNCNAME} ${LINENO}; rm -f "test"; fi 
	return
	if [ "$CONTINUE" == "false" ]
	then
		white
		white "Downloading new  installation script ($SCRIPTNAME), please wait..."
		if [ "`echo $installServer | grep "resources.dmesync.com"`" != "" ]
		then
			download "http://resources.dmesync.com/install/$SCRIPTNAME"
		else
			download "/install/$SCRIPTNAME"
		fi	

		if [ -e $TMPDIR/files/$SCRIPTNAME ] && [ ! -e /tmp/.tmp/1932 ]
		then
			echo -e "USERNAME=$USERNAME\nPASSWORD=$PASSWORD" > /tmp/.tmp_1932
			white "Starting up the new installation script"
			sh $TMPDIR/files/$SCRIPTNAME 
			exit 0
		fi

	fi
}

checkDownload()
{
	# Check status of downloaded file $1 in $WGETLOG
	#log4bash 1 "Checking for download status of file \"$1\"" ${FUNCNAME} ${LINENO}
	
	# Common error messages
	NET_PROBLEM="Problems finding $installServer\n  - Make sure this is a valid DME Install Server\n  - Make sure you can connect to the Internet through port 80 (http)\n  - Otherwise contact your local DME Partner."
	MSG401402403="Problems retrieving from $installServer\n  - Make sure you are connecting to the right DME Install Server\n  - Make sure this is a valid DME Install Server\n  - Otherwise contact your local DME Partner"	
	
	# Set download error to perform errorlogging
	DOWNLOAD_ERROR='false'
	
	if [ "`grep HTTP $WGETLOG.$tmpbasename | tail -n1 | egrep -m1 -o "401"`" != "" ]
	then 
		E_NETWORK='true'
		DOWNLOAD_ERROR='true'
		log4bash 3 "$WGETLOG.$tmpbasename" ${FUNCNAME} ${LINENO}
		_exit "Username or password is incorrect\n  - Make sure you spelled it correctly\n  - Otherwise contact your local DME Partner"
	fi
	
	if [ "$(grep HTTP $WGETLOG.$tmpbasename | grep "Host not found")" != "" ]
	then 
		E_NETWORK='true'
		DOWNLOAD_ERROR='true'
		log4bash 3 "$WGETLOG.$tmpbasename" ${FUNCNAME} ${LINENO}
		_exit "$NET_PROBLEM"
	fi
	if [ "$(grep HTTP $WGETLOG.$tmpbasename | grep "Connection refused")" != "" ]
	then 
		DOWNLOAD_ERROR='true'
		log4bash 3 "$WGETLOG.$tmpbasename" ${FUNCNAME} ${LINENO}
		_exit "$NET_PROBLEM"
	fi
	if [ "$(grep HTTP $WGETLOG.$tmpbasename | egrep "402|403")" != "" ]
	then
		DOWNLOAD_ERROR='true'
		log4bash 3 "$WGETLOG.$tmpbasename" ${FUNCNAME} ${LINENO}
		_exit "$MSG401402403"
	fi
	if [ "$(grep "HTTP" $WGETLOG.$tmpbasename | grep "20 ")" != "" ]
	then
		E_NETWORK='true'
		DOWNLOAD_ERROR='true'
		log4bash 3 "$WGETLOG.$tmpbasename" ${FUNCNAME} ${LINENO}
		_exit "Unknown error from server"
	fi
	
	#if [ "$(grep "HTTP" $WGETLOG.$tmpbasename | grep "200 OK")" != "" ]
	#then 
		#log4bash 1 " - file \"$1\" downloaded from $installServer" ${FUNCNAME} ${LINENO}
	#fi
	if [ "$(grep "HTTP" $WGETLOG.$tmpbasename | grep "already there")" != "" ]
	then 
		log4bash 1 " - file $1 has already been downloaded " ${FUNCNAME} ${LINENO}
	fi
	if [ -f "$WGETLOG.$tmpbasename" ]; then rm -f "$WGETLOG.$tmpbasename"; fi
	rm -f $WGETLOG 2> /dev/null
	rm -f $WGETLOG.$tmpbasename 2> /dev/null


}

createTmpDir()
{
	log4bash 0 "createTmpDir()" ${FUNCNAME} ${LINENO}
	# Create a temporary installation dir
	mkdir -p $TMPDIR
}

isInstalled()
{
	log4bash 0 "isInstalled()" ${FUNCNAME} ${LINENO}
	PRE_CHECK="true"
	if [ -d "/var/dme" ] && [ "$PRE_CHECK" != "true" ]
	then
		white ""
	        warn "Base system already installed"
		white ""
	fi
}

parseArgvForVersionsFileName()
{
	log4bash 0 "parseArgvForVersionsFileName()" ${FUNCNAME} ${LINENO}
	if [ "`basename $0`" != "dme-install.sh" ]
	then
		FILE=`basename $0`
		VERSIONS_FILE_PLACE="`echo $FILE | sed "s,dme-,,g" | sed "s,\.sh,,g"`/"
		warn "This installation is only valid for $VERSIONS_FILE_PLACE"
		white
		VERSIONS_FILE_PLACE_WWW="/release-$VERSIONS_FILE_PLACE/"
	else
		VERSIONS_FILE_PLACE_WWW="/"
	fi
}

getVersions()
{
	log4bash 0 "getVersions()" ${FUNCNAME} ${LINENO}
	# Get a list of releases of the DME software that can be installed
	ABORT=false
	cd $TMPDIR
	rm -f $TMPDIR/versions
	parseArgvForVersionsFileName
	if [ "$GETCONNECTOR" == "true" ]
	then
		OUTPUTFILENAME="conn_versions"
		download "files/connectors/versions"
	fi
	if [ "$VERSIONS_FILE_PLACE_WWW" != "" ]
	then
		download "${VERSIONS_FILE_PLACE_WWW}linux/versions" $installServer
	else
		download "linux/versions" $installServer
	fi

	if [ ! -d $CWD/_files_ ]
	then
		download "linux/scripts/changelog-linux.txt" $installServer
	fi
	dwhite "Changelog downloaded to $TMPDIR/files" ${FUNCNAME} ${LINENO}
	version=""
	if [ "$AUTOSELECT" == "false" ]
	then
		log4bash 1 "Finding the latest release automatically" ${FUNCNAME} ${LINENO}
	fi
	
	if [ "$DEV" != "true" ]
	then
		dwhite "  - Removing any available \"DEV\" versions" 
		grep -i -v "DEV" $TMPDIR/files/versions > $TMPDIR/tmp/versions
		rm -f $TMPDIR/files/versions
		mv $TMPDIR/tmp/versions $TMPDIR/files/versions
	else
		dwhite "  - DEV releases are enabled"
	fi
	if [ "$OLDVERSIONS" != "true" ]
	then
		if [ "$1" != "short" ]
		then
			dwhite "  - Removing any available \"OLD\" versions" 
			grep -i -v "OLD" $TMPDIR/files/versions > $TMPDIR/tmp/versions
			rm -f $TMPDIR/files/versions
			mv $TMPDIR/tmp/versions $TMPDIR/files/versions
		else
			dwhite "  - Removing non Connector related entries"
			grep -i -v ":1.9.4:\|:1.10:\|:2.0:" $TMPDIR/files/versions > $TMPDIR/tmp/versions
			rm -f $TMPDIR/files/versions
			mv $TMPDIR/tmp/versions $TMPDIR/files/versions
		fi
	else
		dwhite "  - OLD releases are enabled"
	fi
	if [ "$UPGRADE35" == "true" ]
	then
		dwhite " - removing all 3.6 entries since it is an upgrade below 3.6"
		grep -i -v ":3.6:" $TMPDIR/files/versions > $TMPDIR/tmp/versions
		rm -f $TMPDIR/files/versions
		mv $TMPDIR/tmp/versions $TMPDIR/files/versions
	fi
	while (true)
	do
		INSTALL='false'
		#clrscr
		if [ "$AUTOSELECT" == "false" ]
		then
			if [ "$1" != "short" ]
			then
				white "Please choose version and release\n"
			else
				white "Please choose DME Server version\n"
			fi
		fi
		#declare -a list list1 list2

		#if [ "$DEBUG" != "true" ]
		#then
		#	white " - debug disabled"
		#	if [ "$DATABASE" == "" ]
		#	then
		#		white " - listing 1"
		#		#list1=( `cat -s $TMPDIR/files/versions | sed "s/ /_/g" | grep -v "^#\|^w\|^-" | sort | grep "^l:1:" | grep -v $VERSIONSFILTER` )
		#		#list1=( `cat -s $TMPDIR/files/versions | grep $ARCH | sed "s/ /_/g" | grep -v "^#\|^w\|^- | sed "s,:GA:,:0:,g" " | sort -d | grep "^l:1:" | grep -v $VERSIONSFILTER` )
		#		list1=( `cat -s $TMPDIR/files/versions | grep $ARCH | sed "s/ /_/g" | grep -v "^#\|^w\|^- | sed "s,:GA:,:0:,g" " | grep "^l:1:" | grep -v $VERSIONSFILTER` )
		#		#list2=( `cat -s $TMPDIR/files/versions | sed "s/ /_/g" | grep -v "^#\|^w\|^-" | sort | grep "^l:0:" | grep -v $VERSIONSFILTER` )
		#		#list2=( `cat -s $TMPDIR/files/versions | grep $ARCH | sed "s/ /_/g" | grep -v "^#\|^w\|^-" | sed "s,:GA:,:0:,g"  | sort -dr | grep "^l:0:" | sort -r | grep -v $VERSIONSFILTER` )
		#		#list2=( `cat -s $TMPDIR/files/versions | grep $ARCH | sed "s/ /_/g" | grep -v "^#\|^w\|^-" | sed "s,:GA:,:0:,g"  | grep "^l:0:" | sort -r | grep -v $VERSIONSFILTER` )
		#		list2=( `cat -s $TMPDIR/files/versions | grep $ARCH | sed "s/ /_/g" | grep -v "^#\|^w\|^-" | sed "s,:GA:,:0:,g"  | grep "^l:0:" | grep -v $VERSIONSFILTER` )
		#	else
		#		white " - listing 2"
		#		#list1=( `cat -s $TMPDIR/files/versions | sed "s/ /_/g" | grep -v "^#\|^w\|^-" | sort | grep "^l:1:" | grep -v $VERSIONSFILTER` )
		#		#list1=( `cat -s $TMPDIR/files/versions | grep $ARCH | sed "s/ /_/g" | grep -v "^#\|^w\|^-" | sed "s,:GA:,:0:,g"  | grep $DATABASE | sort | grep "^l:1:" | grep -v $VERSIONSFILTER` )
		#		list1=( `cat -s $TMPDIR/files/versions | grep $ARCH | sed "s/ /_/g" | grep -v "^#\|^w\|^-" | sed "s,:GA:,:0:,g"  | grep $DATABASE | grep "^l:1:" | grep -v $VERSIONSFILTER` )
		#		#list2=( `cat -s $TMPDIR/files/versions | sed "s/ /_/g" | grep -v "^#\|^w\|^-" | sort | grep "^l:0:" | grep -v $VERSIONSFILTER` )
		#		#list2=( `cat -s $TMPDIR/files/versions | grep $ARCH | sed "s/ /_/g" | grep -v "^#\|^w\|^-" | sed "s,:GA:,:0:,g" | grep $DATABASE | sort -r | grep "^l:0:" | sort -r | grep -v $VERSIONSFILTER` )
		#		#list2=( `cat -s $TMPDIR/files/versions | grep $ARCH | sed "s/ /_/g" | grep -v "^#\|^w\|^-" | sed "s,:GA:,:0:,g" | grep $DATABASE | grep "^l:0:" | grep -v $VERSIONSFILTER` )
		#		list2=( `cat -s $TMPDIR/files/versions | grep $ARCH | sed "s/ /_/g" | grep -v "^#\|^w\|^-" | sed "s,:GA:,:0:,g"  | grep "^l:0:" | grep -v $VERSIONSFILTER` )
		#	fi
		#else
		#	white " - debug enabled"
		#	if [ "$DATABASE" == "" ]
		#	then
		#		dwhite " - listing 1"
		#		dwhite "database == \"\""
		#		#dwhite "list1: cat -s $TMPDIR/files/versions | grep $ARCH | sed \"s/ /_/g\" | grep -v \"^#\|^w\|^-\" | sed \"s,:GA:,:0:,g\"  | sort | grep \"^l:1:\|^dl:1:\" | grep -v $VERSIONSFILTER"
		#		list1=( `cat -s $TMPDIR/files/versions | grep $ARCH | sed "s/ /_/g" | grep -v "^#\|^w\|^-" | sed "s,:GA:,:0:,g"  | grep "^l:1:\|^dl:1:" | grep -v $VERSIONSFILTER` )
		#		#list2=( `cat -s $TMPDIR/files/versions | sed "s/ /_/g" | grep -v "^#\|^w\|^-" | sort | grep "^l:0:" | grep -v $VERSIONSFILTER` )
		#		#dwhite "list2: cat -s $TMPDIR/files/versions | grep $ARCH | sed \"s/ /_/g\" | grep -v \"^#\|^w\|^-\" | sed \"s,:GA:,:0:,g\" | sort -r | grep \"^l:0:\|dl:0:\" | sort -r | grep -v $VERSIONSFILTER"
		#		#list2=( `cat -s $TMPDIR/files/versions | grep $ARCH | sed "s/ /_/g" | grep -v "^#\|^w\|^-" | sed "s,:GA:,:0:,g" | sort -r | grep "^l:0:\|dl:0:" | sort -r | grep -v $VERSIONSFILTER` )
		#		#list2=( `cat -s $TMPDIR/files/versions | grep $ARCH | sed "s/ /_/g" | grep -v "^#\|^w\|^-" | sed "s,:GA:,:0:,g" | grep "^l:0:\|dl:0:" | grep -v $VERSIONSFILTER` )
		#		list2=( `cat -s $TMPDIR/files/versions | grep $ARCH | grep mysql | sed "s/ /_/g" | grep -v "^#\|^w\|^-" | sed "s,:GA:,:0:,g" | grep "^l:0:\|dl:0:" | grep -v $VERSIONSFILTER` )
		#	else
		#		dwhite " - listing 2"
		#		dwhite "Database != \"\""
		#		#dwhite "list1: cat -s $TMPDIR/files/versions | grep $ARCH | sed \"s/ /_/g\" | grep -v \"^#\|^w\|^-\" | sed \"s,:GA:,:0:,g\"  | grep $DATABASE | sort | grep \"^l:1:\|^dl:1:\" | grep -v $VERSIONSFILTER"
		#		#list1=( `cat -s $TMPDIR/files/versions | grep $ARCH | sed "s/ /_/g" | grep -v "^#\|^w\|^-" | sed "s,:GA:,:0:,g"  | grep $DATABASE | sort | grep "^l:1:\|^dl:1:" | grep -v $VERSIONSFILTER` )
		#		list1=( `cat -s $TMPDIR/files/versions | grep $ARCH | sed "s/ /_/g" | grep -v "^#\|^w\|^-" | sed "s,:GA:,:0:,g"  | grep $DATABASE | grep "^l:1:\|^dl:1:" | grep -v $VERSIONSFILTER` )
		#		#list2=( `cat -s $TMPDIR/files/versions | sed "s/ /_/g" | grep -v "^#\|^w\|^-" | sort | grep "^l:0:" | grep -v $VERSIONSFILTER` )
		#		#dwhite "list2: cat -s $TMPDIR/files/versions | grep $ARCH | sed \"s/ /_/g\" | grep -v \"^#\|^w\|^-\" | sed \"s,:GA:,:0:,g\" | grep $DATABASE | sort -r | grep \"^l:\|^dl:\" | sort -r | grep -v $VERSIONSFILTER"
		#		#list2=( `cat -s $TMPDIR/files/versions | grep $ARCH | sed "s/ /_/g" | grep -v "^#\|^w\|^-" | sed "s,:GA:,:0:,g" | grep $DATABASE | sort -r | grep "^l:\|^dl:" | sort -r | grep -v $VERSIONSFILTER` )
		#		list2=( `cat -s $TMPDIR/files/versions | grep $ARCH | sed "s/ /_/g" | grep -v "^#\|^w\|^-" | sed "s,:GA:,:0:,g" | grep $DATABASE | grep "^l:\|^dl:" | grep -v $VERSIONSFILTER | sort -r +2 -3 -t:` )
		#	fi
		#
		#
		#fi
		#list=( "" ${list1[@] } ${list2[@]} )

		declare -a list
		dwhite "DATABASE: $DATABASE"
		dwhite "ARCH: $ARCH"
		#list=( "" `for x in "3.6" "3.5" "3.0" "2.0" "1.10" "1.9.4"; do sort -t: -k 6 -n -r $TMPDIR/files/versions | sed "s, ,_,g" |  grep ":$x:" | grep -v "^#\|$VERSIONSFILTER" | grep $ARCH ; done` )
		list=( "" `for x in "3.6" "3.5" "3.0"; do sort -t: -k 6 -n -r $TMPDIR/files/versions | sed "s, ,_,g" |  grep ":$x:" | grep -v "^#\|$VERSIONSFILTER" | grep $ARCH ; done` )
		if [ "$GETCONNECTOR" == "true" ] || [ "$1" == "short" ]
		then
			dwhite "VERSIONSFILTER = $VERSIONSFILTER"
			if [ "$CREATEOFFLINE" != "true" ]
			then
				white "Getting Connector versions:"
			else
				white "Getting available versions:"
			fi
			white 
			unset list
			#list=( `cat -s $TMPDIR/files/versions | grep i386 | grep mysql | sed "s/ /_/g" | grep -v "^w\|^-" | sed "s,:GA:,:0:,g" | grep "3.0" | sed "s,^#,,g" | grep "^l:" | sort -r | uniq` )
			#list=( "" `cat -s $TMPDIR/files/versions | grep i386 | grep mysql | sed "s/ /_/g" | grep -v "^w\|^-" | sed "s,:GA:,:0:,g" | grep "3.0" | grep "l:\|dl:" | sort -r` )
			#list=( "" `cat -s $TMPDIR/files/versions  | grep i386 | grep mysql | sed "s, ,_,g" | grep "l:" | grep ":3.0\|:3.5\|3.6" | sed "s,#,,g" | sed "s,dl:,l:,g" | grep -v $VERSIONSFILTER`)
			list=( "" `for x in "3.6" "3.5" "3.0"; do sort -t: -k 6 -n -r $TMPDIR/files/versions | sed "s, ,_,g" |  grep ":$x:" | grep -v "^#" | grep $ARCH | grep mysql ; done` )
		fi
		#white "found: ${#list[@]} entries in versions file"
		unset list1 list2
		found=1
		color=0

		for a in $(seq  $((${#list[@]} - 1)))
		do
			b0=`echo ${list[$a]} | cut -d: -f2` # default (1=true)
			b1=`echo ${list[$a]} | cut -d: -f3` # dmes 
			b2=`echo ${list[$a]} | cut -d: -f4 | sed "s/\.//g"` # b_version - "."
			b100=`echo ${list[$a]} | cut -d: -f4` # Version with "."'s 
			b3=`echo ${list[$a]} | cut -d: -f6` # b_release
			b300=`echo ${list[$a]} | cut -d: -f5` # SP
			b5=`echo ${list[$a]} | cut -d: -f8 | sed "s/mysql/MySQL/g" | sed "s/mssql/MS SQL Server/g"` # database
			b6=`echo ${list[$a]} | cut -d: -f9`
			b7=`echo ${list[$a]} | cut -d: -f10`
			b9=`echo ${list[$a]} | cut -d: -f12 | sed "s/_/ /g"`
			if [ "$DDEBUG" == "true" ]
			then
				dwhite "b0 = $b0"
				dwhite "b1 = $b1"
				dwhite "b2 = $b2"
				dwhite "b3 = $b3"
				dwhite "b4 = $b4"
				dwhite "b5 = $b5"
				dwhite "b6 = $b6"
				dwhite "b7 = $b7"
				dwhite "b8 = $b8"
				dwhite "b9 = $b9"
			fi
			# The default installation is the first entry in "versions" that start with "1:" and
			# has support for mysql
			COLOR[0]='\e[39;01m'
			if [ "${b[0]}" == "1" ] 
			then	
				#FOUND[$found]="${b[1]}-R${b[2]}-${b[3]} for ${b[5]}"
				FOUND[$found]="${b1}-R${b2}-${b3} for ${b5}"
				if [ "$AUTOSELECT" == "false" ]
				then
					#white "    $found) ${GOOD}${FOUND[$found]} "
					if [ "$1" == "short" ]
					then
						#white "  $found) `echo ${GOOD}${b[9]} | cut -d, -f1`"
						white "  $found) `echo ${GOOD}${b9} | cut -d, -f1`"
					else
						#white "  $found) ${GOOD}${b[9]}"
						white "  $found) ${GOOD}${b9}"
					fi
					#hite "                with ${b[5]}, JDK ${b[6]} and JBoss ${b[7]}"

					#default_install="$found) -> ${FOUND[$found]}"
					default_install="${FOUND[$found]}"
					default_install_item=$found
				else
					version=$found
					break
				fi
			else
				#FOUND[$found]="${b[1]}-R${b[2]}-${b[3]} for ${b[5]} - (`echo ${list[$a]} | cut -d: -f4`-${b[3]})"
				#FOUND[$found]="${b[1]}-R${b[2]}-${b[3]} for ${b[5]} - (${b[100]}-${b[3]})"
				FOUND[$found]="${b1}-R${b2}-${b3} for ${b5} - (${b100}-${b3})"
				if [ "$AUTOSELECT" == "false" ]
				then
					#white "    $found) ${FOUND[$found]}"
					if [ "$1" == "short" ]
					then
						if [ "$found" -lt "10" ]
						then
							#white "   $found) `echo ${b[9]} | cut -d, -f1`"
							white "   $found) `echo ${b9} | cut -d, -f1`"
						else
							white "  $found) `echo ${b9} | cut -d, -f1`"
						fi
					else
						if [ "$found" -lt "10" ]
						then
							#white "   $found) ${b[9]}"
							white "   $found) ${b9}"
						else
							#white "  $found) ${b[9]}"
							white "  $found) ${b9}"
						fi
					fi
					#white "                with JDK ${b[6]} and JBoss ${b[7]}"
				fi
			fi
			((found+=1))
		done
		if [ "$AUTOSELECT" == "false" ]
		then 
			white ""
			if [ "$default_install" != "" ]
			then
				white  "You can use \"Q\" or \"quit\" to stop installation and return to previous menu"
				white  "You can use \"H\" of \"help\" to get some help understanding the naming convention"
				white
				white "Default install is \"$default_install\""
				whiten "Choose version [default => $default_install_item]: "
			else
				default_install_item=1
				if [ "$GETCONNECTOR" == "true" ]
				then
					white "  R) Return to menu"
					white	
				fi
				whiten "Choose version [default => $default_install_item]: "
			fi
			if [ "$CHOOSEVERSION" == "" ]
			then
				read version
			else
				version=$CHOOSEVERSION
				white "$version"
				unset CHOOSEVERSION
				dwhite "Jumping to version: $CHOOSEVERSION" ${FUNCNAME} ${LINENO}
			fi
			case $version in
				quit|QUIT|q|Q|r|R)
					dwhite "Aborting getVersion()"
					ABORT="true"
					return
				;;
				help|HELP|h|H)
					dmeHelp "DME Version: Naming Convention"
					continue
				;;
			esac

			if [ "$version" == "" ]; then version=$default_install_item; fi
			if [ "${FOUND[$version]}" != "" ]
			then
				INSTALL=${list[$version]}
				if [ "$INSTALL" != "false" ]
				then
					break
				fi	
			else
				warn "Not a valid selection!"
				unset version
				sleep 2
			fi
				
		fi
		if [ "$AUTOSELECT" == "true" ] 
		then	
			INSTALL=${list[$version]}
			white "Upgrading to version ${FOUND[$version]} if possible"
			dwhite "  - found version ${FOUND[$version]}" ${FUNCNAME} ${LINENO}
			break
		fi
		
	done
	# Set filename
	declare -a list
	list=( `echo $INSTALL | sed "s/:/ /g"` ) 
	b_default=${list[1]}
	b_short=${list[2]}
	b_version=${list[3]}
	b_dmes="`echo ${list[3]} | sed "s/\.//g"`"
	b_release=${list[5]}

	if [ "$b_release" == "" ] || [ "$b_release" == "0" ] || [ "$b_release" == "GA" ]
	then 
		b_release=0
	fi
	b_sp=${list[4]}
	b_arch=${list[6]}
	b_database=${list[7]}
	case $b_database in
		mysql)	DATABASE="mysql" ;;
		mssql)  DATABASE="mssql" ;;
	esac
	b_java=${list[8]}
	b_jboss=${list[9]}
	b_ear=${list[10]}
	b_name="${b_short}-R`echo $b_version | sed "s/\.//g"`-${b_release}"
	dwhite "  - b_version : $b_version"
	dwhite "  - b_release : $b_release"
	dwhite "  - b_sp      : $b_sp"
	dwhite "  - b_database: $b_database"
	dwhite "  - b_java    : $b_java"
}

resumeFile()
{
	log4bash 0 "resumeFile()" ${FUNCNAME} ${LINENO}
	if [ ! -d /var/dme/instances ]
	then
		log4bash 0 " - old filesystem layout - resumefile not supported" ${FUNCNAME} ${LINENO}
		return
	fi

	if [ ! -d /var/dme/etc/ ]
	then
		return
	fi
	white
	if [ "$1" == "" ]
	then
		white "Please wait while updating system information"
	else
		white "$1"
	fi

	b_default=1
	b_short="DMES"
	# Get the version of the installed DME
	if [ -e /var/dme/instances/base/deploy/dme_nam.ear -o -e /var/dme/instances/base/deploy/dme_nam_mssql.ear -o -e /var/dme/instances/base/deploy/dme-sync.ear ] 
	then
		EARDIR="deploy"
	else
		EARDIR="app"
	fi
	if [ -e /var/dme/instances/base/$EARDIR/dme_nam.ear ]
	then
		EARFILE="dme_nam.ear"
		b_database=mysql
	fi
	if [ -e /var/dme/instances/base/$EARDIR/dme_nam_mssql.ear ]
	then
		EARFILE="dme_nam_mssql.ear"
		b_database=mssql
	fi
	if [ -e /var/dme/instances/base/deploy/dme-sync.ear ]
	then
		EARFILE="dme-sync.ear"
		if [ "`grep mysql /var/dme/instances/base/etc/jboss/dmebaseDB-ds.xml`" != "" ]
		then
			dwhite " - dmebaseDB-ds.xml has MySQL JDBC driver information"
			b_database=mysql
		else
			dwhite " - dmebaseDB-ds.xml has MS SQL JDBC driver information"
			b_database=mssql
		fi
	fi
	dwhite "EARFILE = $EARFILE"
	log4bash 1 "b_version: $b_version" ${FUNCNAME} ${LINENO}
	log4bash 1 "Using EARDIR: $EARDIR" ${FUNCNAME} ${LINENO}
	if [ "$b_ear" == "" ]
	then
		b_ear=`ls /var/dme/instances/base/$EARDIR/$EARFILE 2> /dev/null`
		b_ear=`basename $b_ear 2> /dev/null`
		if [ "$b_ear" == "" ]
		then
			dwhite " - setting EARFIle to dme-sync.ear"
			b_ear=dme-sync.ear
		fi
	fi
	cd $TMPDIR/tmp
	log4bash 1 "unzip -f /var/dme/instances/base/$EARDIR/$EARFILE META-INF/MANIFEST.MF 2> /dev/null 1> /dev/null" ${FUNCNAME} ${LINENO}
	dwhite "unzip -c /var/dme/instances/base/$EARDIR/$EARFILE META-INF/MANIFEST.MF 2> /dev/null"
	TMP=`unzip -c /var/dme/instances/base/$EARDIR/$EARFILE META-INF/MANIFEST.MF 2> /dev/null`
	log4bash 1 "$TMP"
	echo "$TMP" > /tmp/aaa
	#b_version=`echo "$TMP" | grep "^Version" | sed "s, [ ]*, ,g" | cut -d" " -f2 | sed "s,[^0-9.],,g"`
	#b_release=`echo "$TMP" | grep "^Version" | sed "s, [ ]*, ,g" | cut -d"-" -f3 | sed "s,),,g" | sed "s, ,,g"`
	b_version=`cat /tmp/aaa  | grep ^Version: | cut -d" " -f2`
	b_release=`cat /tmp/aaa  | grep ^Version: | cut -d" " -f5`
	b_sp=`cat /tmp/aaa  | grep ^Version: | cut -d" " -f3 | sed "s,\,,,g"`
	#dwhite "$TMP"
	#dwhite "`cat /tmp/aaa`"
	dwhite "b_version=$b_version"
	dwhite "b_release=$b_release"
	dwhite "b_sp=$b_sp"
	if [ "`echo $b_release | sed "s,[^0-9],,g"`" == "" ]
	then
		log4bash 1 "Mangled MANIFIEST.MF info, trying different method"
		b_release=`grep "^Version: " /tmp/aaa  | cut -d: -f3- | cut -d" " -f2`
	fi
	if [ "$b_release" == "" ]; then b_release=0; fi
	b_dmes=`echo $b_version | sed "s,[\.,],,g" | sed "s, [ ]*,,g"`
	b_arch=`uname -i`
	b_arch=`uname -i`
	b_java=`rpm -qa | grep jdk | sort | grep fcs | tail -n1 | cut -d"-" -f2 `
	b_jboss=`ls -l /usr/local/jboss | cut -d">" -f2 | cut -d"-" -f2 | tr '\r' ' ' | sed "s, [ ]*,,g"`
	b_name="${b_short}-R${b_dmes}-${b_release}"
	DATABASE=$b_database
	cd - 2> /dev/null 1> /dev/null

	# Create a resume file that can be used later
	echo "######################" > $RESUME
	echo "#   DO NOT EDIT !!!  #" >> $RESUME
	echo "######################" >> $RESUME
	echo "" >> $RESUME
	echo "# This file is auto-generated and is used by the installation script" >> $RESUME
	echo "# If you change values in the file, you will lose the installation" >> $RESUME
	echo "# and can only restore by reinstalling everything, including getting" >> $RESUME
	echo "# a license key from your local DME Partner or Excitor A/S, Denmark." >> $RESUME
	echo "" >> $RESUME
	echo "b_default=$b_default" >> $RESUME
	echo "b_short=$b_short" >> $RESUME
	echo "b_sp=$b_sp" >> $RESUME
	echo "b_version=$b_version" >> $RESUME
	echo "b_dmes=$b_dmes" >> $RESUME
	echo "b_release=`echo $b_release | cut -d" " -f1`" >> $RESUME
	echo "b_arch=$b_arch" >> $RESUME
	echo "b_database=$b_database" >> $RESUME
	echo "b_java=$b_java" >> $RESUME
	echo "b_jboss=$b_jboss" >> $RESUME
	echo "b_ear=$b_ear" >> $RESUME
	echo "b_name=`echo $b_name | cut -d" " -f1`" >> $RESUME
	echo "DATABASE=$DATABASE" >> $RESUME
	echo "installServer=http://`echo $installServer | sed "s,http://,,g"`" >> $RESUME
	sed -i "s, LSS,,g" /var/dme/etc/do_not_touch 2> /dev/null
	sed -i "s, $,,g" /var/dme/etc/do_not_touch 2> /dev/null
	if [ -e $RESUME ]
	then
		sed -i "s,,,g" $RESUME 2> /dev/null
		sed -i "s, [ ]*$,,g" $RESUME 2> /dev/null
		log4bash 1 "Resume file created: $RESUME" ${FUNCNAME} ${LINENO}
	fi
	mv -f $RESUME /var/dme/etc/do_not_touch 2> /dev/null
	dwhite "Resume file has been updated" ${FUNCNAME} ${LINENO}
}



# Start with a clrscr screen
#echo -n '' > $START_PWD/install-dme.log
doStart


# Check if there is at correctly setup connection to the internet
log4bash 1 "Checking network set up" ${FUNCNAME} ${LINENO}
ipCheck

# Check to see if we have DNS or not
#dnsCheck ## DEBUG - uncomment when ready for release !!!

# Check connection to server and see if we can use it

checkServer

# Begin the installation
createTmpDir

# Clear the screen and greet the user
topScreen "DME Server Installation"
white "The DME installer needs your credentials to continue."
white "The credentials is for the Excitor RFS system or "
white "Excitors DME license site."
white
# Get username and password from the user
if [ ! -d _files_ ] 
then
	getUsernameAndPassword
fi

dwhite "Downloading MD5 check sum file from http://install.excitor.dk/install/md5sum.txt" 
cd $TMPDIR/files/
wget -N http://install.excitor.dk/install/md5sum.txt -O $TMPDIR/files/md5sum.txt 1> /dev/null 2> /dev/null


download "test" $installServer

#white
#white "Please wait while initializing..."
#sleep 2

# Disable Ctrl-C for the remainder of the script
#trap '' 2

# Show the main menu
rm -f $TMPDIR/files/main_menu.sh 2> /dev/null
download "linux/scripts/main_menu.sh"
. $TMPDIR/files/main_menu.sh
menu

# Stop the log
finished
reset


