#!/bin/bash 
# #################################################################################
# Exceed TurboX Client Launcher
# © Rocket Software, Inc. or its affiliates. All Rights Reserved.
# ROCKET SOFTWARE, INC. CONFIDENTIAL
# #################################################################################
# install
# #################################################################################

# master install script for Exceed TurboX Client Launcher, start install log, 
# check for essential files and permissions then call component install scripts

if [ "${DEBUGINSTALL}" = "1" ] ; then
	set -x
	export XDG_UTILS_DEBUG_LEVEL=5
	DEBUGSH="set -x"
else
	DEBUGSH=
fi


VERSION=12.0
APP_NAME="Exceed TurboX Client Launcher"
PROD_NAME="${APP_NAME}"
ABORTING="Installation aborted"

read_yesno()
{
# accepts y, n, yes, no; converts input to lowercase
# by default null input is "no", $1 overrides yndefault (n, y, none, block)
# yes: returns 0 (useful for: if read_yesno ; then )
# no: returns 1; Enter: returns default: 0, 1, or 2

	# set default answer if null response
	yndefault=$1
	if [ -z "${yndefault}" ] ; then
		yndefault=n
	fi
	
	while true ; do
		
		read answer
		#convert to lowercase
		answer=`${ECHO} ${answer}| tr [:upper:] [:lower:]`
		${ECHO}
		
		case "${answer}" in
			y|yes )
				return 0
				;;
			n|no )
				return 1
				;;
			"" )
				case "${yndefault}" in
					y ) return 0 ;;
					n ) return 1 ;;
					none ) return 2 ;;
					block )
						${ECHO} "Invalid input. Please try again."
						;;
				esac
				;;
			* )
				${ECHO} "Invalid input '${answer}'. Please try again."
				;;
		esac
	
	done
}

read_noyes()
{
# no: returns 0 (useful for: if read_noyes ; then )

	read_yesno $*
	resp=$?
	if [ $resp -eq 0 ] ; then
		return 1
	elif [ $resp -eq 1 ] ; then
		return 0
	else
		return $resp
	fi
}

acceptlicense()
{
	LICENSE_ACCEPT_Q="Please press [y] to accept, [n] to decline or <Enter> to read again: \c"
	
	if [ -z "${LICENSETEXT}" ] ; then
		LICENSETEXT=./licensetext
	fi
	
	if [ ! -r "${LICENSETEXT}" ] ; then
		${ECHO} "Cannot read file ${LICENSETEXT}."
		exit 1
	fi
	
	while true ; do 
		clear
		more ${LICENSETEXT}
		
		${ECHO} 
		${ECHO} "${LICENSE_ACCEPT_Q}"
		
		read_yesno none
		resp=$?
		
		if [ "${resp}" = "0" ] ; then
			return 0
		fi
		
		if [ "${resp}" = "1" ] ; then
			return 1
		fi
	
	done
}

usage()
{
	${ECHO} "Usage: $0 [-s responsefile ]"
}

strlen()
{
	# `expr length "$*"` is not supported in older systems
	strlenresult=`expr "$*" : '.*'`
	return ${strlenresult}
}

printsectmessage()
{
	if [ "${bSilent}" = "1" ] ; then
		return
	fi
	# calculate proper # of = for this header
	strlen $*
	slen=$?
	lpos=0
	suffix=
	while test ${lpos} -lt  ${slen}
	do
		suffix="${suffix}="
		lpos=`expr ${lpos} + 1`
	done
	${ECHO}
	${ECHO} $*
	${ECHO} ${suffix}
	${ECHO}
}

printtitlemessage()
{
	if [ "${bSilent}" = "1" ] ; then
		return
	fi
	# calculate proper # of = for this header
	strlen $*
	slen=$?
	inmarg="    "
	strlen "${inmarg}"
	mlen=$?
	titlewmarg=`echo "${inmarg}$*${inmarg}"`
	strlen "${titlewmarg}"
	tslen=$?
	tslen=`expr ${tslen} - 2`
	lpos=0
	border=
	mborder=
	while test ${lpos} -lt  ${tslen}
	do
		border=`echo ${border}'='`
		mborder=`echo "${mborder} "`
		lpos=`expr ${lpos} + 1`
	done
	${ECHO}
	${ECHO} "${border}"
	${ECHO} "${titlewmarg}"
	${ECHO} "${border}"
	${ECHO}
}


cd_and_exit()
{
	resetCDir
	exit $1
}

test_GREP()
{
	${ECHO} ${GREP} -e GREP "$0" > /dev/null 2>&1
	${GREP} -e GREP "$0" > /dev/null 2>&1
	if [ $? -gt 0 ] ; then
		return 1
	else
		return 0
	fi
}

find_good_grep()
{
	GREP=`which grep`
	test_GREP
	if [ $? -gt 0 ] ; then
		GREP=`which egrep`
		test_GREP
		if [ $? -gt 0 ] ; then
			GREP=/usr/xpg4/bin/grep
			test_GREP
			if [ $? -gt 0 ] ; then
				${ECHO} "FATAL ERROR: The grep version on this machine is too old.  It needs to be equivalent to GNU grep."
				cd_and_exit 1
			fi
		fi
	fi
	export GREP
	return
}

test_STRINGS()
{
	${STRINGS} -v > /dev/null 2>&1
	if [ $? -gt 0 ] ; then
		return 1
	else
		return 0
	fi
}

find_good_STRINGS()
{
	STRINGS=`which strings`
	test_STRINGS
	if [ $? -gt 0 ] ; then
		STRINGS=/usr/bin/strings
		test_STRINGS
		if [ $? -gt 0 ] ; then
			${ECHO} "FATAL ERROR: Unable to locate strings executable.  Please install strings before installing again."
 			${ECHO} "For Debian-based distributions"
			${ECHO} "      sudo apt-get install binutils"
			${ECHO} ""
			${ECHO} "For RPM-based distributions"
			${ECHO} "      sudo yum install binutils"
			cd_and_exit 1
		fi
	fi
	export STRINGS
	return
}


final_check_for_launcher_dependencies()
{
	# no matter what we will try to run etxlauncher to print its version, we'll find it if runs or not
	errorlaunch=`${binetxlaunchercontrol} --version 2>&1`
	if [ $? -gt 0 ] ; then
		# cannot launch - see if we can be more specific
		if [ "${thisOS}" = "${osLinux}" ] ; then
			# we need GLIBC 2.3 in order to work. Do our best to detect that
			glibc_version=2.3
			find_glibc ${glibc_version}
			result=$?
			if [ $result -eq 0 ] ; then
				errorlaunch="Required libc.so does not contain GLIBC_${glibc_version}."
			else
				${ECHO} "Looking for GTK2 dependency"
				# we need gtk2 x11 support - check for that
				val=`which ldconfig`
				if [ $? -eq 0 ] ; then
					val=`ldconfig -p|grep libgtk-x11.2.0.so.0 2>&1`
					if [ $? -gt 0 ] ; then
						errorlaunch="Unable to locate gtk2. Please install libgtk2 package."
					else
						${ECHO} "Found GTK2 library"
					fi
				else
					val=`which dpkg`
					if [ $? -eq 0 ] ; then
						val=`dpkg -l libgtk2.0-bin | grep -e '^i' 2>&1`
						if [ $? -gt 0 ] ; then
							errorlaunch="Unable to locate gtk2. Please install libgtk2.0-bin package."
						else
							${ECHO} "Found libgtk2.0-bin package"
						fi
					fi
				fi
			fi
		fi

		if [ ! "${bSilent}" = "1" ] ; then
			${ECHO}
			${ECHO} "${PROD_NAME} will not function without appropriate dependencies"
			${ECHO} "${errorlaunch}"
			${ECHO} "Would you like to continue anyway?"
			${ECHO} "[y]es or [n]o (<Enter> for no): \c"
			if read_yesno; then
				logIncident "1" "${logfile}" "${PROD_NAME} installing without appropriate dependencies ${errorlaunch}" "${PROD_INSTALL_TIME}"
				return
			else
				${ECHO} "Installation was cancelled by user."
				cd_and_exit 1
			fi
		fi
		logIncident "1" "${logfile}" "${PROD_NAME} cannot be installed without appropriate dependencies. ${errorlaunch}" "${PROD_INSTALL_TIME}"
		cd_and_exit 1
	fi
}


logIncident()
{
	if [ "${1}" = "1" ] ; then
		incidentCategory="INFORMATION"
	elif [ "${1}" = "2" ] ; then
		incidentCategory="WARNING"
	elif [ "${1}" = "3" ] ; then
		incidentCategory="FATAL ERROR"
	else
		incidentCategory="UNKNOWN"
	fi
	
	thisLogFile="${2}"
	smallTab="  "
	
	${ECHO} "${incidentCategory}: `basename ${0}`" >> "${thisLogFile}"
	
	if [ ! "${3}x" = "x" ] ; then
		${ECHO} "${smallTab}${3}" >> "${thisLogFile}"
	fi
	
	if [ ! "${4}x" = "x" ] ; then
		${ECHO} "${smallTab}${4}" >> "${thisLogFile}"
	fi
	
	if [ ! "${5}x" = "x" ] ; then
		${ECHO} "${smallTab}${5}" >> "${thisLogFile}"
	fi
	
	if [ ! "${6}x" = "x" ] ; then
		${ECHO} "${smallTab}${6}" >> "${thisLogFile}"
	fi
	
	if [ ! "${7}x" = "x" ] ; then
		${ECHO} "${smallTab}${7}" >> "${thisLogFile}"
	fi
	
	if [ ! "${8}x" = "x" ] ; then
		${ECHO} "${smallTab}${8}" >> "${thisLogFile}"
	fi
	
	if [ ! "${9}x" = "x" ] ; then
		${ECHO} "${smallTab}${9}" >> "${thisLogFile}"
	fi
	
	${ECHO} >> "${thisLogFile}"
}

resolveDir()
{
	# resolve links - $0 may be a softlink
	thisPRG="${1}"
	
	while [ -h "$thisPRG" ]; do
		ls_ld=`ls -ld "$thisPRG"`
		this_link=`expr "${ls_ld}" : '.*-> \(.*\)$'`
		
		if expr "${this_link}" : '/.*' > /dev/null; then
			thisPRG="${this_link}"
		else
			thisPRG=`dirname "${thisPRG}"`/"${this_link}"
		fi
	done

	# -- we only want to check fully resolved path
	if [ "${3}" = "CD" ] ; then
		eval ${2}="${thisPRG}"
		return
	fi
	
	CDir="${PWD}"
	
	thisPrgDirName="`dirname ${thisPRG}`"
	
	cd "${thisPrgDirName}" > /dev/null 2>&1
	cd .. > /dev/null 2>&1 
	
	Here=`pwd`
	#declare "${2}=${Here}"
	eval "$(printf "%q=%q" "${2}" "${Here}")"

	cd "${CDir}"

}

getInstallDir()
{
	resolveDir $0 InstallDir
}

resetCDir()
{
	cd "${CDir}" > /dev/null 2>&1
}

finalize()
{
	resetCDir
	${ECHO} "${PROD_NAME} Installation Complete"
	${ECHO} "${PROD_NAME} Installation Complete" >> "$logfile"
}

initialize()
{
	init_variables $*
	export_globals
	display_install_banner
	areYouRoot
	rootUserResult=$?
	init_log_file
	verify_write_dir
}

isItSUSELinux()
{
	if [ -d "/etc/init.d" ] ; then
		isSUSE=1
	fi
}

getThisPlatform()
{
	osAix=aix
	osLinux=linux
	osSolaris=solaris
	osHPUX=hpux
	
	archPpc=ppc
	archi586=i586
	archx86_64=x86_64
	archSparc=sparc
	archParisc=parisc
	
	unknown=unknown
	
	thisOS=${unknown}
	thisArch=${unknown}
	
	thisUname=`uname`
	
	fgrepOptions="-c -i"
	optionL="-L"
	
	hasi86=`uname -a | grep ${fgrepOptions} i386`
	
	if [ ${hasi86} = "0" ] ; then
		hasi86=`uname -a | grep ${fgrepOptions} i686`
	fi
	
	isx86_64=`uname -a | grep ${fgrepOptions} x86_64`
	
	if [ ${hasi86} = "0" ] ; then
		if [ ! ${isx86_64} = "0" ] ; then
			thisArch=${archx86_64}
		fi
	else
		thisArch=${archi586}
	fi
	
	case ${thisUname} in
		AIX )
			thisOS=${osAix}
			thisArch=${archPpc}
			;;
		Linux )
			thisOS=${osLinux}
			isItSUSELinux
			;;
		SunOS )
			thisOS=${osSolaris}
			if [ ${hasi86}=0 ] ; then
				thisArch=${archSparc}
				optionL="-h"
			fi
			;;
		HP-UX )
			thisOS=${osHPUX}
			thisArch=${archParisc}
			;;
		* )
			;;
	esac
}


addSectionHeader()
{
	if [ "${bSilent}" = "1" ] ; then
		return
	fi
	
	${ECHO} ""
	${ECHO} "${1}"
	${ECHO} "${2}"
	${ECHO} ""
}

init_variables()
{
	logDir="${InstallDir}/installlogs"
	initFile="${logDir}/init.d"
	logfile="${logDir}/install.log"

	binDir="${InstallDir}/bin"
	binetxlaunchercontrol="${binDir}/etxlauncher"

	conf_dir="${InstallDir}/conf"

	thisUname=`uname`
	isSparc=`uname -a | ${GREP} -c sparc`

	# TODO - determine if our "latest" instances of xdg are older than local copies
	XDGMIME="${binDir}/xdg-mime"
	XDGICONRESOURCE="${binDir}/xdg-icon-resource"
	export XDGMIME
	export XDGICONRESOURCE
}

export_globals()
{
	export bSilent
	export bBootStart
}

chmodThisDir()
{
	if [ ! "${bSilent}" = "1" ] ; then
		${ECHO} ".\c" 
	fi
	
	chmod $2 "$1" > /dev/null 2>&1
	
	for f in `ls "$1"` ;
	do
		chmodThisFile "$1/$f" $2 $3
	done
}

chmodThisFile()
{
	if [ -f "$1" ] ; then
		chmod $3 "$1" > /dev/null 2>&1
	elif [ -d "$1" ] ; then
		chmodThisDir "$1" $2 $3
	fi
}

test_ECHO()
{
	${ECHO} -e "test\c" | grep "\-e" > /dev/null
	if [ $? -gt 0 ] ; then
		# -e is supported so add it
		ECHO="${ECHO} -e"
	fi
}

find_good_ECHO()
{
	ECHO=`which echo`
	test_ECHO
	export ECHO
}

set_platform_opts()
{
	find_good_ECHO
	if [ ${OSTYPE:="UNKNOWN"} = "Linux" \
			-o $OSTYPE = "linux-gnu" \
			-o $OSTYPE = "linux" \
			]; then
		USERADDOPTS="-M"
	else
		USERADDOPTS=
	fi

	export USERADDOPTS
}

display_install_banner()
{
	if [ "${bSilent}" = "1" ] ; then
		return
	fi
	
	InstallBanner="INSTALL - ${PROD_NAME}"
	
	clear
	printtitlemessage "${InstallBanner}"

}

init_log_file()
{
	if [ $ONLYGCONF -gt 0 ] ; then
		return
	fi
	if [ ! -d "${logDir}" ] ; then
		mkdir "${logDir}"
	fi
	
	logfile="${logDir}/install.log"
	
	touch "$logfile" 2>/dev/null
	
	if [ ! "${bSilent}" = "1" ] ; then
		if [ ! -w "$logfile" ] ; then
			${ECHO} "We are unable to create the log $logfile."
			${ECHO} "Would you like to continue anyway?"
			${ECHO} "[y]es or [n]o (<Enter> for no): \c"
			if read_yesno ; then
				logfile=/dev/null
			else
				${ECHO} $ABORTING
				cd_and_exit 1
			fi
		fi
	fi
	
	${ECHO} > "$logfile"
	${ECHO} "${PROD_NAME} Installation Log" >> "$logfile"
	${ECHO} "#####################################################" >> "$logfile"
	${ECHO} "" >> "$logfile"
	${ECHO} "" >> "$logfile"
	
	logIncident "1" "${logfile}" "${LOG_DATE}"
}

verify_write_dir()
{
	touch "${conf_dir}/test_write" 2>/dev/null
	if [ ! -w "${conf_dir}/test_write" ] ; then
		if [ ! "${bSilent}" = "1" ] ; then
			${ECHO} "We are unable to write into ${conf_dir}."
			${ECHO} "The installation cannot continue. Please check user permissions and try again."
		fi
		cd_and_exit 1
	fi
	rm "${conf_dir}/test_write" 2>/dev/null
}

handle_license()
{
	if [ "${bSilent}" = "1" ] ; then
		return
	fi

	LICENSE_TITLE="Licensing"
	LICENSE_CONTINUE_Q="Please press <Enter> to view License Agreement: \c"
	LICENSE_ACCEPTED="License accepted"
	LICENSE_NOT_ACCEPTED="License not accepted"

	printsectmessage "${LICENSE_TITLE}"
	
	${ECHO} "${LICENSE_CONTINUE_Q}"
	
	read foo
	
	if acceptlicense ; then
		logIncident "1" "${logfile}" "${LICENSE_ACCEPTED}"
	else
		logIncident "3" "${logfile}" "${LICENSE_NOT_ACCEPTED}"
		${ECHO} "$ABORTING"
		cd_and_exit 1
	fi
	
	clear
}

areYouRoot()
{
	wai=whoami
	noWhoAmI=`which ${wai} | ${GREP} -c "no ${wai}"`
	
	if [ "${noWhoAmI}" = "1" -a  -x /usr/ucb/${wai} ] ; then
		wai=/usr/ucb/${wai}
		noWhoAmI=0
	fi
	
	if [ "${noWhoAmI}" = "0" -a ! "`${wai}`" = "root" ] ; then
		${ECHO}
		${ECHO} "Current user does not have 'root' privileges."
		${ECHO} "Installing ${PROD_NAME} in user mode."
		${ECHO}
		return 1
	else
		${ECHO}
		${ECHO} "Current user has 'root' privileges"
		${ECHO} "Installing ${PROD_NAME} in system mode."
		${ECHO}
		logfile=${logDir}/install-allusers.log
	fi
	return 0
}

display_warning_message()
{
	${ECHO}
	${ECHO} "Warning: ${this_msg}"
}

show_this_warning()
{
	this_log="$1"
	
	if [ -r ${this_log} ] ; then
		rm -f "${this_log}"
	else
		this_msg="$2"
		display_warning_message
	fi
}

setInstallCompleteFlag()
{
	${ECHO} "${InstallCompleteFlag}" >> "${ETXCNProps}"
}

change_owner()
{
	chown $*
}

wrap_it_up()
{
	logIncident "1" "${logfile}" "${PROD_INSTALL_OK}" "${PROD_INSTALL_TIME}"
}

xdgmime_system_replacement_default_generic()
{
    # $1 is vendor-name.desktop
    # $2 is mime/type
    # Add $2=$1 to $share_applications/defaults.list
    default_file="$share_applications/defaults.list"
    [ -f "$default_file" ] || touch "$default_file"
    awk -v mimetype="$2" -v application="$1" '
    BEGIN {
        prefix=mimetype "="
        indefault=0
        added=0
        blanks=0
        found=0
    }
    {
        suppress=0
        if (index($0, "[Default Applications]") == 1) {
            indefault=1
            found=1
        } else if (index($0, "[") == 1) {
            if (!added && indefault) {
                print prefix application
                added=1
            }
            indefault=0
        } else if ($0 == "") {
            suppress=1
            blanks++
        } else if (indefault && !added && index($0, prefix) == 1) {
                $0=prefix application
                added=1
        }
        if (!suppress) {
            while (blanks > 0) {
                print ""
                blanks--
            }
            print $0
        }
    }
    END {
        if (!added) {
            if (!found) {
                print ""
                print "[Default Applications]"
            }
            print prefix application
        }
        while (blanks > 0) {
            print ""
            blanks--
        }
    }
' "$default_file" > "${default_file}.new" && mv "${default_file}.new" "$default_file"
}

xdgmime_system_replacement_mimeapps_generic()
{
    # $1 is vendor-name.desktop
    # $2 is mime/type
    # Add $2=$1 to $share_applications/mimeapps.list
    default_file="$share_applications/mimeapps.list"
    [ -f "$default_file" ] || touch "$default_file"
    awk -v mimetype="$2" -v application="$1" '
    BEGIN {
        prefix=mimetype "="
        indefault=0
        inadded=0
        adddefault=0
        addadded=0
        blanks=0
        founddefault=0
        foundadded=0
    }
    {
        suppress=0
        if (index($0, "[Default Applications]") == 1) {
            indefault=1
            founddefault=1
        } else if (index($0, "[Added Applications]") == 1) {
            inadded=1
            foundadded=1
        } else if (index($0, "[") == 1) {
            if (!adddefault && indefault) {
                print prefix application
                adddefault=1
            } else if (!addadded && inadded) {
               print prefix application
               addadded=1
           }
           inadded=0
           indefault=0
        } else if ($0 == "") {
            suppress=1
            blanks++
        } else if (indefault && !adddefault && index($0, prefix) == 1) {
                $0=prefix application
                adddefault=1
        } else if (inadded && !addadded && index($0, prefix) == 1) {
                $0=prefix application
                addadded=1
        }
        if (!suppress) {
            while (blanks > 0) {
                print ""
                blanks--
            }
            print $0
        }
    }
    END {
        if (!adddefault) {
            if (!founddefault) {
                print ""
                print "[Default Applications]"
            }
            print prefix application
        }
        if (!adddefault) {
            if (!foundadded) {
                print ""
                print "[Added Applications]"
            }
            print prefix application
        }
        while (blanks > 0) {
            print ""
            blanks--
        }
    }
' "$default_file" > "${default_file}.new" && mv "${default_file}.new" "$default_file"
}

xdgmime_system_replacement_mimeapps_xdg()
{
    # $1 is vendor-name.desktop
    # $2 is mime/type
    # Add $2=$1 to /etc/xdg/mimeapps.list
    if [ ! -d /etc/xdg ] ; then
	return
    fi
    default_file="/etc/xdg/mimeapps.list"
    [ -f "$default_file" ] || touch "$default_file"
    awk -v mimetype="$2" -v application="$1" '
    BEGIN {
        prefix=mimetype "="
        indefault=0
        inadded=0
        adddefault=0
        addadded=0
        blanks=0
        founddefault=0
        foundadded=0
    }
    {
        suppress=0
        if (index($0, "[Default Applications]") == 1) {
            indefault=1
            founddefault=1
        } else if (index($0, "[Added Applications]") == 1) {
            inadded=1
            foundadded=1
        } else if (index($0, "[") == 1) {
            if (!adddefault && indefault) {
                print prefix application
                adddefault=1
            } else if (!addadded && inadded) {
               print prefix application
               addadded=1
           }
           inadded=0
           indefault=0
        } else if ($0 == "") {
            suppress=1
            blanks++
        } else if (indefault && !adddefault && index($0, prefix) == 1) {
                $0=prefix application
                adddefault=1
        } else if (inadded && !addadded && index($0, prefix) == 1) {
                $0=prefix application
                addadded=1
        }
        if (!suppress) {
            while (blanks > 0) {
                print ""
                blanks--
            }
            print $0
        }
    }
    END {
        if (!adddefault) {
            if (!founddefault) {
                print ""
                print "[Default Applications]"
            }
            print prefix application
        }
        if (!adddefault) {
            if (!foundadded) {
                print ""
                print "[Added Applications]"
            }
            print prefix application
        }
        while (blanks > 0) {
            print ""
            blanks--
        }
    }
' "$default_file" > "${default_file}.new" && mv "${default_file}.new" "$default_file"
}

handle_desktop()
{
	# $1  "system" or "user"  [Not used]
	desktopfileid=etxlauncher12.desktop
	etxdesktopfile="${conf_dir}/${desktopfileid}"
	etxdesktopfiletemplate="${conf_dir}/${desktopfileid}.template"
	installed_etxdesktopfile=${share_applications}/${desktopfileid}

	if [ ! -f "${etxdesktopfiletemplate}" ] ; then
		${ECHO} "error ${etxdesktopfiletemplate} does not exist. Verify install package."
		${ECHO} $ABORTING
		cd_and_exit 1
	fi
	# Use etxlauncher12.desktop.template to create etxlauncher12.desktop file
	if [ -f "${etxdesktopfile}" ] ; then
		#${ECHO} "${etxdesktopfile} exists and will be replaced with new content."
		rm -f "${etxdesktopfile}" > /dev/null 2>&1
	fi
	tmp_sh=$(mktemp -q --tmpdir="$(pwd)" etxlaunch_tmp_desktopfileid.XXXXXXXXXX.sh 2> /dev/null)
	if [ $? -ne 0 ]; then
	    tmp_sh="$(pwd)/tmp-etxlaunch_tmp_desktopfileid.sh"
	fi
	cat > "$tmp_sh" << __tmp_EOF__
	sed 's|__ETXLAUNCHERHOME__|${InstallDir}|;s|__LAUNCHBINARY__|${LaunchBinary}|;s|__TERMINAL__|${TerminalRequired}|' < "${etxdesktopfiletemplate}" > "${etxdesktopfile}"
__tmp_EOF__
	chmod +x "$tmp_sh"
	$tmp_sh
	rm -f "$tmp_sh" > /dev/null 2>&1
	# Make sure the applications folder is available before updating xdgmine
	mkdir ${share_applications} > /dev/null 2>&1
	
	if [ "$1" = "system" ] ; then
		# xdg-mime does not update global /usr/share/applications/defaults.list file (no system mode)
		# so provide our own
		xdgmime_system_replacement_default_generic ${desktopfileid} x-scheme-handler/etx12
		xdgmime_system_replacement_mimeapps_generic ${desktopfileid} x-scheme-handler/etx12
		xdgmime_system_replacement_mimeapps_xdg ${desktopfileid} x-scheme-handler/etx12
		handle_mime_gio system ${desktopfileid} x-scheme-handler/etx12

		xdgmime_system_replacement_default_generic ${desktopfileid} x-scheme-handler/etxsr12
		xdgmime_system_replacement_mimeapps_generic ${desktopfileid} x-scheme-handler/etxsr12
		xdgmime_system_replacement_mimeapps_xdg ${desktopfileid} x-scheme-handler/etxsr12
		handle_mime_gio system ${desktopfileid} x-scheme-handler/etxsr12
	else
		${DEBUGSH} "${XDGMIME}" default ${desktopfileid} x-scheme-handler/etx12 > /dev/null 2>&1
		handle_mime_gio user ${desktopfileid} x-scheme-handler/etx12
		${DEBUGSH} "${XDGMIME}" default ${desktopfileid} x-scheme-handler/etxsr12 > /dev/null 2>&1
		handle_mime_gio user ${desktopfileid} x-scheme-handler/etxsr12
	fi

	# we want to replace any existing file with our new version
	cp -f "${etxdesktopfile}" ${installed_etxdesktopfile}

}

handle_mime_xml_XDG()
{
	# $1  "system" or "user"
	${ECHO} "Registering XDG specific ETX 12 x-scheme-handler"
	xml_file=x-scheme-handler-etx12.xml
	xmlsr_file=x-scheme-handler-etxsr12.xml
	#  cp "${conf_dir}/${xml_file}" ${share_mimexml}/${xml_file}
	if [ "$1" = "system" ] ; then
		${DEBUGSH} "${XDGMIME}" install --mode system "${conf_dir}/${xml_file}" > /dev/null 2>&1
		${DEBUGSH} "${XDGMIME}" install --mode system "${conf_dir}/${xmlsr_file}" > /dev/null 2>&1
	else
		${DEBUGSH} "${XDGMIME}" install "${conf_dir}/${xml_file}" > /dev/null 2>&1
		${DEBUGSH} "${XDGMIME}" install "${conf_dir}/${xmlsr_file}" > /dev/null 2>&1
	fi
}

handle_mime_xml_Gconf()
{
	# if we have gconftool-2 support then register ourselves in there as well 
	gconftool2=`which gconftool-2 2>&1`
	if [ $? -eq 0 ] ; then
		${ECHO} "Registering GConf specific ETX12 url handler"
		if [ "$1" = "system" ] ; then
			# put them in system default
			gconftool-2 --direct --config-source xml:readwrite:/etc/gconf/gconf.xml.defaults -t string -s /desktop/gnome/url-handlers/etx12/command "${InstallDir}/bin/${LaunchBinary} %s"
			gconftool-2 --direct --config-source xml:readwrite:/etc/gconf/gconf.xml.defaults -t bool   -s /desktop/gnome/url-handlers/etx12/needs_terminal ${TerminalRequired}
			gconftool-2 --direct --config-source xml:readwrite:/etc/gconf/gconf.xml.defaults -t bool   -s /desktop/gnome/url-handlers/etx12/enabled true

			gconftool-2 --direct --config-source xml:readwrite:/etc/gconf/gconf.xml.defaults -t string -s /desktop/gnome/url-handlers/etxsr12/command "${InstallDir}/bin/${LaunchBinary} %s"
			gconftool-2 --direct --config-source xml:readwrite:/etc/gconf/gconf.xml.defaults -t bool   -s /desktop/gnome/url-handlers/etxsr12/needs_terminal ${TerminalRequired}
			gconftool-2 --direct --config-source xml:readwrite:/etc/gconf/gconf.xml.defaults -t bool   -s /desktop/gnome/url-handlers/etxsr12/enabled true
			${ECHO} "Warning: global gconf setting changes will not be active for users who are"
			${ECHO} "already logged in.  These users will need to log out and back in."
		fi
		# gconftool requires access for restarting gconfd if none avail then we'll get errors
		# ${DBUS_SESSION_BUS_ADDRESS}
		# turn it on
		gconftool-2 -t string -s /desktop/gnome/url-handlers/etx12/command "${InstallDir}/bin/${LaunchBinary} %s" > /dev/null 2>&1
		gconftool-2 -t bool   -s /desktop/gnome/url-handlers/etx12/needs_terminal ${TerminalRequired} > /dev/null 2>&1
		gconftool-2 -t bool   -s /desktop/gnome/url-handlers/etx12/enabled true  > /dev/null 2>&1

		gconftool-2 -t string -s /desktop/gnome/url-handlers/etxsr12/command "${InstallDir}/bin/${LaunchBinary} %s" > /dev/null 2>&1
		gconftool-2 -t bool   -s /desktop/gnome/url-handlers/etxsr12/needs_terminal ${TerminalRequired} > /dev/null 2>&1
		gconftool-2 -t bool   -s /desktop/gnome/url-handlers/etxsr12/enabled true  > /dev/null 2>&1
		# install schema?
	fi
}

handle_mime_xml_Kde()
{
	# if we have kinfocenter support then register ourselves as kde as well
	kinfocenter=`which kinfocenter 2>&1`
	if [ $? -eq 0 ] ; then
		if [ "x${kde_services_dir}" = "x" ] ; then
			return
		fi
		#for KDE we can place a .protocol file in the correct KDE folder
		${ECHO} "Registering KDE specific ETX12 protocol file"
		
		# create the protocol file from our template
		protocolfileid=etx12.protocol
		etxprotocolfile="${conf_dir}/${protocolfileid}"
		etxprotocolfiletemplate="${conf_dir}/${protocolfileid}.template"
		installed_etxprotocolfile=${kde_services_dir}/${protocolfileid}
		if [ ! -f ${etxprotocolfiletemplate} ] ; then
			${ECHO} "error ${etxprotocolfiletemplate} does not exist. Verify install package."
			${ECHO} $ABORTING
			cd_and_exit 1
		fi
		# Use etx12.protocol.template to create etx12.protocol file
		if [ -f ${etxprotocolfile} ] ; then
			#${ECHO} "${etxprotocolfile} exists and will be replaced with new content."
			rm -f "${etxprotocolfile}" > /dev/null 2>&1
		fi
		# create the protocol sr file from our sr template
		protocolsrfileid=etxsr12.protocol
		etxsrprotocolfile=${conf_dir}/${protocolsrfileid}
		etxsrprotocolfiletemplate=${conf_dir}/${protocolsrfileid}.template
		installed_etxsrprotocolfile=${kde_services_dir}/${etxsrprotocolfile}
		if [ ! -f ${installed_etxsrprotocolfile} ] ; then
			${ECHO} "error ${installed_etxsrprotocolfile} does not exist. Verify install package."
			${ECHO} $ABORTING
			cd_and_exit 1
		fi
		# Use etxsr12.protocol.template to create etxsr12.protocol file
		if [ -f ${etxsrprotocolfile} ] ; then
			#${ECHO} "${etxsrprotocolfile} exists and will be replaced with new content."
			rm -f "${etxsrprotocolfile}" > /dev/null 2>&1
		fi
		tmp_sh=/tmp/etxlaunch_tmp_desktopfileid.sh
		cat > $tmp_sh << __tmp_EOF2__
		sed 's|__ETXLAUNCHERHOME__|${InstallDir}|;s|__LAUNCHBINARY__|${LaunchBinary}|' < "${etxprotocolfiletemplate}" > "${etxprotocolfile}"
		sed 's|__ETXLAUNCHERHOME__|${InstallDir}|;s|__LAUNCHBINARY__|${LaunchBinary}|' < "${etxsrprotocolfiletemplate}" > "${etxsrprotocolfile}"
__tmp_EOF2__
		chmod +x $tmp_sh
		$tmp_sh
		rm -f $tmp_sh > /dev/null 2>&1

		if [ ! -e ${kde_services_dir} ] ; then
			${ECHO} "Warning: KDE ETX12 protocol registration failed.  The KDE services folder for user"
			${ECHO} "'${kde_services_dir}' does not exist.  If your browser"
			${ECHO} "is not launching ETX12 sessions, please create this folder and install again."
			${ECHO}
		else
			cp -f "${etxprotocolfile}" "${installed_etxprotocolfile}"
			cp -f "${etxsrprotocolfile}" "${installed_etxsrprotocolfile}"
		fi
	fi
}

handle_mime_gio()
{
	# if we have gio then register $2 file
	gio_app=`which gio 2>&1`
	if [ $? -eq 0 ] ; then
		cd "${share_applications}"
		${gio_app} mime $3 $2
		if [ $? -gt 0 ] ; then
			${ECHO} "WARNING - failed to register $3 handler"
			${ECHO} ""
			${ECHO} "You may be able to resolve by running:"
			${ECHO} "cd ${share_applications}"
			${ECHO} "gio mime $3 $2"
			${ECHO} "WARNING - failed to register $3 handler" >> "${logfile}"
			${ECHO} "" >> "${logfile}"
			${ECHO} "You may be able to resolve by running:" >> "${logfile}"
			${ECHO} "cd ${share_applications}" >> "${logfile}"
			${ECHO} "gio mime $3 $2" >> "${logfile}"
		else
			${gio_app} mime $3
		fi
		cd "${InstallDir}/bin"
	fi
}

handle_mime_xml()
{
	${ECHO} Registering x-scheme-handler-etx12 as mime
	${ECHO} Registering x-scheme-handler-etx12 as mime >> "${logfile}" 
	${ECHO} Registering x-scheme-handler-etxsr12 as mime
	${ECHO} Registering x-scheme-handler-etxsr12 as mime >> "${logfile}" 
	# $1  "system" or "user"
	handle_mime_xml_XDG $1
	handle_mime_xml_Gconf $1
	handle_mime_xml_Kde $1
}


handle_desktop_icons()
{
	${ECHO} Registering Desktop icon 
	${ECHO} Registering Desktop icon  >> "${logfile}"
	# $1  "system" or "user" [Not used]
	sml_icon=etxlauncher.58.png
	lrg_icon=etxlauncher.128.png
	mime_icon=x-scheme-handler-etx12
	mimesr_icon=x-scheme-handler-etxsr12

	#cp ${InstallDir}/icons/${sml_icon}  ${share_pixmaps}/${sml_icon}
	#cp ${InstallDir}/icons/${sml_icon}  ${share_pixmaps}/${mime_icon}
	
	if [ "$1" = "system" ] ; then
		${DEBUGSH} "${XDGICONRESOURCE}" install --mode system --context mimetypes --size  58 "${InstallDir}/icons/${sml_icon}" ${mime_icon} > /dev/null 2>&1
		${DEBUGSH} "${XDGICONRESOURCE}" install --mode system --context mimetypes --size 128 "${InstallDir}/icons/${lrg_icon}" ${mime_icon} > /dev/null 2>&1
		${DEBUGSH} "${XDGICONRESOURCE}" install --mode system --context mimetypes --size  58 "${InstallDir}/icons/${sml_icon}" ${mimesr_icon} > /dev/null 2>&1
		${DEBUGSH} "${XDGICONRESOURCE}" install --mode system --context mimetypes --size 128 "${InstallDir}/icons/${lrg_icon}" ${mimesr_icon} > /dev/null 2>&1
	else
		${DEBUGSH} "${XDGICONRESOURCE}" install --context mimetypes --size  58 "${InstallDir}/icons/${sml_icon}" ${mime_icon} > /dev/null 2>&1
		${DEBUGSH} "${XDGICONRESOURCE}" install --context mimetypes --size 128 "${InstallDir}/icons/${lrg_icon}" ${mime_icon} > /dev/null 2>&1
		${DEBUGSH} "${XDGICONRESOURCE}" install --context mimetypes --size  58 "${InstallDir}/icons/${sml_icon}" ${mimesr_icon} > /dev/null 2>&1
		${DEBUGSH} "${XDGICONRESOURCE}" install --context mimetypes --size 128 "${InstallDir}/icons/${lrg_icon}" ${mimesr_icon} > /dev/null 2>&1
	fi
}

handle_desktop_xdg_refresh()
{
	${ECHO} "Updating mime database... this may take some time."
	# $1  "system" or "user"  [Not used]
	update-desktop-database ${share_root_folder} > /dev/null 2>&1
	# - etx-23799 - failure to handle .local/share/applications in user explicitly
	if [ "$1" = "user" ] ; then
		update-desktop-database ~/.local/share/applications > /dev/null 2>&1
	fi
	if [ ! -d "${share_root_folder}/packages" ] ; then
		mkdir ${share_root_folder}/packages > /dev/null 2>&1
	fi
	update-mime-database ${share_root_folder} > /dev/null 2>&1
}


find_glibc()
{
	glibc_version=$1

	${ECHO} "Locating libc.so with GLIBC_$glibc_version version"
	glibc_found=0

	tmp_glibc=/tmp/etxlaunch_glibc_test$glibc_version
	${ECHO} "`/sbin/ldconfig -p | grep libc.so`" | sed 's/ //g'|sed 's/=>/ /g' > $tmp_glibc
	while read line
	do
			# echo "line: " $line
			glib_details=`echo $line |awk '{print $1}'`
			glib_path=`echo $line | awk '{print $2}'`

			if [ "${DEBUGINSTALL}" = "1" ] ; then
				${ECHO} "Details:   $glib_details"
				${ECHO} "   Path:   $glib_path"
			fi

			supported=`${STRINGS} $glib_path | grep "GLIBC_$glibc_version"`
			strlen $supported
			glibc_found=$?
			if [ $glibc_found -gt 0 ] ; then
					break
			fi
	done < $tmp_glibc
	rm -f $tmp_glibc > /dev/null 2>&1
	return $glibc_found
}

handle_debug_launcher()
{
	if [ $DEBUG -gt 0 ] ; then
		LaunchBinary=debug.sh
		TerminalRequired=true

		${ECHO} "Debug flag enabled.  Each launch will now bring up terminal"

		cat > ${InstallDir}/bin/debug.sh << __tmp_EOF3__
#!/bin/bash
echo "Launching debug etxlauncher terminal"
"${InstallDir}/bin/etxlauncher" \$*
echo "Press a key to exit"
read resp
__tmp_EOF3__
		chmod +x "${InstallDir}/bin/debug.sh"

	else
		LaunchBinary=etxlauncher
		TerminalRequired=false
	fi
}

main_install()
{
	cd "${InstallDir}/bin"
	
	final_check_for_launcher_dependencies

	handle_license

	handle_debug_launcher

	## E.g kde4-config --path services/home/rduser/.kde/share/kde4/services/:/usr/share/kde4/services/
	# Find KDE3 services directory
	kde_user_service_dir=
	kde_global_service_dir=
	kde_global_service_dirs=`kde${KDE_SESSION_VERSION}-config --path services 2> /dev/null`
	# ${ECHO}"kde_global_service_dirs: $kde_global_service_dirs"
	first=
	for x in `echo $kde_global_service_dirs | sed 's/:/ /g'` ; do
		if [ -z "$first" ] ; then
			first=false
			kde_user_service_dir="$x"
		elif [ -w $x ] ; then
			kde_global_service_dir="$x"
		fi
	done
	# ${ECHO} "kde_user_service_dir: $kde_user_service_dir"
	# ${ECHO} "kde_global_service_dir: $kde_global_service_dir"


	if [ ${rootUserResult}  -eq 0 ] ; then
		system_or_user=system
		xdg_system_dirs="$XDG_DATA_DIRS"
		[ -n "$xdg_system_dirs" ] || xdg_system_dirs=/usr/local/share:/usr/share
		for x in `echo $xdg_system_dirs | sed 's/:/ /g'`; do
 			# -- do not allow use of /root - ETX-19421
			if [[ $x == "/root/"* ]] ; then
				echo "Skip using folder $x as system XDG folder."
			else
				if [ -w $x ] ; then
					share_root_folder="$x"
					break
				fi
			fi
		done
		if [ -z "$share_root_folder" ] ; then
			${ECHO} "Cannot determine system XDG folder."
			cd_and_exit 1
		fi
		kde_services_dir="${kde_global_service_dir%/}"
	else
		system_or_user=user
		xdg_user_dir="$XDG_DATA_HOME"
		[ -n "$xdg_user_dir" ] || xdg_user_dir="$HOME/.local/share"
		for x in `echo $xdg_user_dir | sed 's/:/ /g'`; do
			if [ -w $x ] ; then
				share_root_folder="$x"
				break
			fi
		done
		if [ -z "$share_root_folder" ] ; then
			share_root_folder=~/.local/share
			mkdir ~/.local  > /dev/null 2>&1
			mkdir ~/.local/share > /dev/null 2>&1
		fi
		kde_services_dir="${kde_user_service_dir%/}"
	fi
	share_applications=${share_root_folder}/applications
	share_mimexml=${share_root_folder}/mime/packages
	share_pixmaps==${share_root_folder}/pixmaps

	if [ ${ONLYGCONF} -gt 0 ] ; then
		# fail if we do not already have desktop file
		if [ ! -f "${conf_dir}/etxlauncher12.desktop" ] ; then
			${ECHO} "To use -onlygconf option you must have already have installed as root"
			cd_and_exit 1
		fi
		handle_mime_xml_Gconf  $system_or_user
	else

		if [ "${RegisterMime}" = "1" ] ; then
			handle_mime_xml  $system_or_user
			handle_desktop_icons  $system_or_user
		fi

		if [ "${InstallDesktop}" = "1" ] ; then
			handle_desktop $system_or_user
			handle_desktop_xdg_refresh $system_or_user
		fi

		handle_auto_patch $system_or_user
		
		if [ "${system_or_user=user}" = "user" ] ; then
			# we can attempt to register binary
			"${InstallDir}/bin/etxlauncher" -register
		else
			${ECHO} 
			${ECHO} "For Firefox users, please make sure each user runs \"etxlauncher -register\" command to register etxlauncher with Firefox."
			${ECHO} 
		fi
	fi
	wrap_it_up
}


readThisSectionKeyValueForThisVariable()
{
	thisPropFile=$1
	thisSection=$2
	thisKey=$3
	thisKeyFullName=${thisSection}.${thisKey}
	
	tmp_value=`${GREP} "${thisKeyFullName}=" "${thisPropFile}" 2> /dev/null | cut -f2- -d=`
	ret_value=`echo ${tmp_value}|tr -d '\r\n\t'`
	eval ${thisKey}="${ret_value}" > /dev/null 2>&1
}

readThisSectionKeys()
{
	thisPropFile="$1"
	thisSection="$2"
	theseKeys="$3"
	
	for thisKey in ${theseKeys}
	do
		readThisSectionKeyValueForThisVariable "${thisPropFile}" "${thisSection}" ${thisKey}
	done
}


readResponseFile()
{
	thisResponseFile="$1"
	
	if [ ! -f "${thisResponseFile}" ] ; then
		${ECHO} "FATAL ERROR: Silent mode response file '${thisResponseFile}' does not exist!"
		cd_and_exit 1
	fi
	
	theseKeys="RegisterMime InstallDesktop"
	readThisSectionKeys "${thisResponseFile}" "install.etxlauncher" "${theseKeys}"
}


get_params()
{
	builtinResponseFile="${InstallDir}/conf/builtin.resp"

	RegisterMime="1"
	InstallDesktop="1"
	DEBUG=0
	ONLYGCONF=0

	while [ ! -z "${1}" ] 
	do
		
		case "${1}" in
		-s )
			if [ -z "$2" ] ; then
				usage
			fi
			shift
			bSilent="1"
			readResponseFile "$1"
			;;
		-debug )
			DEBUG=1
			;;
		-onlygconf )
			ONLYGCONF=1
			;;
		* )
			${ECHO} "Invalid option: ${1}"
			cd_and_exit 1
			;;
		esac
		
		shift
	done
}


handle_auto_patch()
{
        # if we see bin/patch file we will run it automatically
        if [ ! -x "${binDir}/patch" ] ; then
                return
        fi

        # either we run it silently passing our own responsefile for answers or
        # we run it in patch apply mode (since we are not installed it will
        # not ask to reboot the server)
        if [ "${bSilent}" = "1" ] ; then
                logIncident "1" "${logfile}" "${binDir}/patch -install -s ${thisResponseFile} was run."
                "${binDir}/patch" -install -s "${thisResponseFile}"
        else
                PATCHING_TITLE="Patching"
                printsectmessage "${PATCHING_TITLE}"
                logIncident "1" "${logfile}" "${binDir}/patch -install  was run."
                "${binDir}/patch" -install
        fi
}

doIt()
{
	getThisPlatform
	set_platform_opts
	find_good_grep
	find_good_STRINGS
	getInstallDir
	get_params $*
	initialize
	main_install
	finalize
}

doIt $*

