#!/bin/bash
#
# Driver Install Script
# Copyright (c) 2005-2021 Kodak Alaris Inc.
#
#
# Error Codes:
# --------------------------------------------------------------------
# 0  success
#
# 1  printed usage/help info
# 2  must be run from root account
# 3  invalid command-line option
# 4  invalid operating system
# 5  hal is not installed, but is required (user must install it)
# 6  scanner was connected
# 7  no longer used
# 8  invalid package (extra or missing files)
#
# 10 did not accept EULA
# 11 did not want to upgrade OpenUSB and/or TWAIN
# 12 no longer used
# 13 no longer used
# 14 SANE not installed and did not want to run without a SANE driver
# 15 no longer used
# 16 did not want to do install
#
# 20 no longer used
# 21 no longer used
# 22 no longer used
# 23 needed OpenUSB is not in this installer
# 24 multiarch-support no installed (required for libudev0)
# 25 kernel version is lower than what is supported
#
# 30 no longer used
#
# 40 no longer used
# 41 no longer used
# 42 libudev0 installation error (install failed)
# 43 no longer used
# 44 OpenUSB installation error (install failed)
# 45 libudev0 installation error (install failed)
# 46 TWAIN DSM installation error (install failed)
# 47 Scanner Package installation error (install failed)
#
# 50 Bad Argument(s) for 'Setup and Connect Scanner'
# 51 Setup error (scs executable cannot be found)
# 52 Scanner not found
#
# 99 Coding error
#
#
#
# Version
# --------------------------------------------------------------------
# 06/04/20 - Added support for NeoKylin 7
# 09/11/20 - Re-done to support OSes for generically
# 12/15/20 - post install items now in packages's .spec file
# 02/07/21 - supports OpenUSB being in driver;s lib folder



################################################################################
# Initialize product specific variables
################################################################################
dialog="KODAK S2000w Scanners"
model=s2000w
modeldir=kds_s2000w
mfgdir=kodak
versioncd=5.2
vids=( 29cc )
flatbedmodeldirs=(  )
flatbedpgknames=(  )
libhasdsmusb=1



################################################################################
# Initialize key variables
################################################################################
strdistrobit=""     # 32-bit or 64-bit Distro string
distro64bit=0       # Is the distro 64-bit?
strdistro=""        # What Linux distro are we running on?
verdistro=""        # The distro's version
strdistropkg=""     # packages to install (i.e. .deb or .rpm)
strdistrodesc=""    # distro's description string (if we can get it)
strdistrodist=""    # distro's distribution string
installOpenusb=0    # Do we have to install OpenUSB?
removeOpenusb=0     # Do we need to remove an older version of OpenUSB?
halInstalled=0      # Is 'hal' installed?
installlibudev0=0   # install our provided libudev0? (for libudev1 systems)
installTwainDsm=0   # Do we have to install a new version of the TWAIN DSM?
removeTwainDsm=0    # Do we have to remove an older version of the TWAIN DSM?
saneInstalled=0     # Is 'sane' installed?
dpkgpath=""         # What is the path to dpkg (.deb distros)?
seLinuxCheck=0      # Do we need to check for SELinux?



################################################################################
# Installer Functions
################################################################################


# clean out the install directory, but leave install log
clean_instdir()
{
	# is there still a temp folder?
	if [ -d $instdir ]; then
		# clean out the temp directory, but leave any leftover install log
		for file in "$instdir"/*
		do
			if [ ! -f "$file" ] || [ "$file" != "$installlogfile" ]; then
				rm -rf "$file"
			fi
		done
	fi
}

# create install log and temp folder
install_init()
{
	# Figure out the temporary directory and copy all the packages there
	if [ "$TMPDIR" == "" ]; then
		TMPDIR=/tmp
	fi

	instdir="$TMPDIR"/$modeldir

	# create name of install log
	installlogfile="$instdir"/install.log

	# make sure the folder is cleaned out (but leave any leftover install log)
	clean_instdir

	# make sure directory exists
	mkdir -p "$instdir"
}

# copy the install log to product specific one
install_end()
{
	scannerpath="/opt/$mfgdir/$modeldir"
	installedpath="$scannerpath/install"

	# if opt folder, then driver installed (At some point),
	# so copy the log file contents
	if [ -d $scannerpath ]; then
		if [ ! -d "$installedpath" ]; then
			# no install folder, so create it and just file
			mkdir -p "$installedpath"
			chmod 666 "$installedpath"
			cp "$installlogfile" "$installedpath/install.log"
			chmod 644 "$installedpath/install.log"
		else
			# need to append contents to the existing file
			cat "$installlogfile" >> "$installedpath/install.log"
		fi

		# done with install log, so remove everything
		# (don't want to append the log again)
		rm -rf "$instdir"
	else
		# get rid of everything except the install log
		# (want to try and append the data next install)
		clean_instdir
	fi

	exit $1
}

# check for command-line parameters (and they can be in any place)
check_commandline()
{
	# do we need to print the usage?
	if [ "$1" == "-h" ] || [ "$1" == "--h" ] || [ "$1" == "-help" ] || [ "$1" == "--help" ] || [ "$1" == "-H" ] || [ "$1" == "--H" ]; then
		echo ""
		echo "Usage: $0"
		echo "       or"
		echo "       $0 --default [--nostatus] [--nosaneok]"
		echo "       or"
		echo "       $0 --nostatus"
		echo "       or"
		echo "       $0 --silent [--nosaneok]"
		echo ""
		echo "    --default       will automatically select default responses so the installation"
		echo "                    will continue. any problems will be echo'd to the terminal."
		echo ""
		echo "    --nostatus      will not echo any status messages to the terminal."
		echo ""
		echo "    --silent        nothing is echo'd to the terminal window and it will act as if"
		echo "                    --default was also on the command line. must use the return"
		echo "                    code to see if there is any error."
		echo "                    NOTE: package install status will be echo'd"
		echo ""
		echo "    --nosaneok      if SANE is not installed, then allow the installation continue."
		echo "                    this will automatically select responses so the install"
		echo "                    continues without the SANE driver (will have to use TWAIN)."
		echo ""
		echo "    --usepkgdeb     if installer cannot determine which package type to use, then"
		echo "                    this will automatially select DEB packages (i.e. .deb)."
		echo ""
		echo "    --usepkgrpm     if installer cannot determine which package type to use, then"
		echo "                    this will automatially select RPM packages (i.e. .rpm)."
		echo ""
		exit 1
	fi

	echo_installfile ""
	echo_installfile "[*** `date` ***   command-line: $*]"

	# assume no bad arguments
	badargs=""

	# initialize all options, then parse the command line
	defaultinstall=0
	statusinstall=0
	silentinstall=0
	nosaneok=0
	usepkgdeb=0
	usepkgrpm=0
	for cmdOpt in ${*:1}
	do
		if [ "$cmdOpt" == "--default" ]; then
			defaultinstall=1
		elif [ "$cmdOpt" == "--nostatus" ]; then
			statusinstall=1
		elif [ "$cmdOpt" == "--silent" ]; then
			silentinstall=1
		elif [ "$cmdOpt" == "--nosaneok" ]; then
			nosaneok=1
		elif [ "$cmdOpt" == "--usepkgdeb" ]; then
			usepkgdeb=1
		elif [ "$cmdOpt" == "--usepkgrpm" ]; then
			usepkgrpm=1
		elif [ "$cmdOpt" != "" ]; then
			badargs="$badargs $cmdOpt"
		fi
	done

	# make sure --no*ok was used with the correct options
	if [ $nosaneok == 1 ]; then
		if [ $defaultinstall == 0 ] && [ $silentinstall == 0 ]; then
			badargs="$badargs --nosaneok"
		fi
	fi

	# if any invalid optionarguments, then just exit.
	if [ "$badargs" != "" ]; then
		echo_silent ""
		echo_silent ""
		echo_silent "******************************"
		echo_silent "Invalid command-line options: $badargs"
		echo_silent "For list of options, type: $0 --help"
		echo_silent ""
		install_end 3
	fi
}

# echo line to the install log, even if the line was hidden by
# the user; that way we can see all the status.
# if the line is hidden, it will be prefixed with given charater
# in $1:
#    d - line hidden because --default is on
#    s - line hidden because --nostatus is on
#    * - line hidden because --silent is on
# 
lastlinehaven=0
echo_installfile()
{
	# if line hidden from user, then pull out the text into $origstring
	if [ "$1" == "d" ] || [ "$1" == "s" ] || [ "$1" == "*" ]; then
		lineprefix="$1 "
		origstring="${*:2}"
	else
		lineprefix=""
		origstring="$*"
	fi

	# depending on how we get called, the "-n" maybe the entire 1st
	# parameter OR it maybe the first part of the 1st parameter
	echowithn=0
	if [ "$origstring" == "-n" ]; then
		echowithn=1
		echostring="${origstring:2}"
	elif [ "${origstring:0:3}" == "-n " ]; then
		echowithn=1
		echostring="${origstring:3}"
	elif [ "${origstring:0:3}" == "-n." ]; then
		echowithn=1
		echostring="${origstring:3}"
	else
		echostring="$origstring"
	fi

	# if the last line did not include a new-line, then don't re-echo the prefix
	if [ $lastlinehaven == 1 ]; then
		lineprefix=""
	fi

	# echo with the "-n" if needed
	if [ $echowithn == 1 ]; then
		lastlinehaven=1
		echo -n "$lineprefix$echostring" >> "$installlogfile"
	else
		lastlinehaven=0
		echo "$lineprefix$echostring" >> "$installlogfile"
	fi
}

# This function will echo given all items if NOT in default mode
echo_default()
{
	if [ $defaultinstall == 1 ]; then
		echo_installfile "d" "$*"
		return
	fi

	# in case silent mode is also on, we need to check that
	echo_silent "$*"
}

# This function will echo given all items if NOT in status mode
echo_status()
{
	if [ $statusinstall == 1 ]; then
		echo_installfile "s" "$*"
		return
	fi

	# in case silent mode is also on, we need to check that
	echo_silent "$*"
}

# This function will echo given all items if NOT in silent mode
echo_silent()
{
	if [ $silentinstall == 1 ]; then
		echo_installfile "*" "$*"
		return
	fi
	echo_installfile "$*"

	# depending on how we get called, the "-n" maybe the entire 1st
	# parameter OR it maybe the first part of the 1st parameter
	if [ "$1" == "-n" ]; then
		echo -n "${*:2}"
		return;
	fi
	if [ "${1:0:3}" == "-n " ]; then
		echo -n "${1:3}"
		return;
	fi
	if [ "${1:0:3}" == "-n." ]; then
		echo -n "${1:3}"
		return;
	fi
	echo "$*"
}

# This function will read from the command-line and put into the given
# variable name if NOT in default mode; otherwise, it will set the
# given variable name so the 'default' is used
#
# $1 - name of variable to fill in with the result
# $2 - default action when nothing is entered
# $3 - default to use if in 'default' or 'silent' mode
read_default()
{
	# if in default mode OR silent mode, then use default value
	if [ $defaultinstall == 1 ] || [ $silentinstall == 1 ]; then
		readsilenttmp=$3
	else
		read readsilenttmp
	fi

	# handle all variants of what the user may type and convert to
	# a common value
	# NOTE: currently only care about Yes and No
	case "$readsilenttmp" in
		Y|y|YES|yes|Yes)
			readsilenttmp="Y"
			;;
		n|N|NO|No|no)
			readsilenttmp="N"
			;;
	######################################
	# and a few letters for configuration
		a|A)
			readsilenttmp="A"
			;;
		e|E)
			readsilenttmp="E"
			;;
		u|U)
			readsilenttmp="U"
			;;
		w|W)
			readsilenttmp="W"
			;;
		*)
			readsilenttmp=$2
			;;
	esac

	eval $1=$readsilenttmp
	echo_installfile $readsilenttmp
}

# This function prompts the user to press enter and waits until they do
# before exiting. The only argument is the optional error code for exit
exit_and_pause()
{
	# Exit the script and use 'read' to pause
	echo_default
	echo_default "Press the 'Enter' key to exit this installation..."
	read_default installOption
	install_end $1
}

# This function prints the 'completed message' and exits
print_completed_message()
{
	# Print the 'completed message' and exit
	echo_status ""
	echo_status ""
	echo_status "******************************"
	echo_status "Software installation is complete"
	echo_status ""
	install_end 0
}

# This function prints the 'not completed message' and exits
print_not_completed_message()
{
	# Print the 'not completed message' and exit
	echo_status ""
	echo_status ""
	echo_status "******************************"
	echo_status "Software installation has not been completed."
	echo_status ""
	install_end $1
}

# This function prints the 'cancelled message' and exits
print_cancelled_message()
{

	# Print the 'cancelled message' and exit
	echo_status ""
	echo_status ""
	if [ "$2" != "" ]; then		# if cancel message given, then print it always
		echo_silent "Cancelled: $2"
		echo_silent ""
	fi
	echo_status "******************************"
	echo_status "Software installation has been cancelled."
	echo_status "No software has been installed or updated."
	echo_status ""
	install_end $1
}

# This function prints the License Agreement and prompts
# the user to continue or exit.
print_license_agreement()
{
	echo_default "******************************"
	echo_default "Kodak Alaris Inc."
	echo_default "SOFTWARE END USER LICENSE AGREEMENT"
	echo_default ""
	echo_default "Read the following terms and conditions carefully before"
	echo_default "using this Software.  Use of this Software indicates your"
	echo_default "acceptance of these terms and conditions.  If you do not"
	echo_default "agree with the terms and conditions, or any of them, you"
	echo_default "should promptly return the Software in its package in its"
	echo_default "entirety for a full refund."
	echo_default ""
	echo_default "LICENSE"
	echo_default ""
	echo_default "Grant of License:  Kodak Alaris Inc. (\"Alaris\") grants"
	echo_default "you a license to use one copy of the enclosed software"
	echo_default "program(s) (the \"Software\") subject to the license"
	echo_default "restrictions set forth below."
	echo_default ""
	echo_default "Restrictions on Use:  You may use the Software only on"
	echo_default "one computer at a time.  For each additional computer on"
	echo_default "which the Software is running at the same time, you will"
	echo_default "need an additional licensed copy of the Software.  You may"
	echo_default "copy the Software as necessary to enable you to use the"
	echo_default "Software as described above."
	echo_default ""
	echo_default "Transfer of Software:  You may permanently transfer the"
	echo_default "Software to another party if the other party agrees to"
	echo_default "accept the terms and conditions of this license and you"
	echo_default "retain no copies of the Software."
	echo_default ""
	echo_default "Diagnostic Software:   Software used to maintain Equipment"
	echo_default "(including diagnosing performance failures)"
	echo_default "(\"Diagnostic Software\") may be embedded, bundled, packaged,"
	echo_default "or provided separately.  Diagnostic Software and the manner"
	echo_default "in which it is implemented constitute valuable proprietary"
	echo_default "intellectual property of Alaris.  You acknowledge and agree"
	echo_default "that possession of the Diagnostic Software grants you no"
	echo_default "right either of ownership or of use of the Diagnostic"
	echo_default "Software except as stated here.  Unless you are separately"
	echo_default "licensed by Alaris to do so, you shall not use, reproduce,"
	echo_default "distribute or disclose the Diagnostic Software for any"
	echo_default "purpose whatsoever, nor will you allow any other person,"
	echo_default "for consideration or no consideration, to do so."
	echo_default "Notwithstanding the foregoing, your express written license"
	echo_default "rights from Alaris may include the right to use the Diagnostic"
	echo_default "Software exclusively on the specific [Alaris] Equipment for"
	echo_default "which such Diagnostic Software was intended.  You further"
	echo_default "consent that at any time, including after the expiration of"
	echo_default "any warranty stated herein, Alaris may access, directly or"
	echo_default "remotely, the Equipment in order to prevent unauthorized use,"
	echo_default "reproduction or distribution of the Diagnostic Software."
	echo_default ""
	echo_default "Copyright:  The Software is owned by Alaris or its suppliers"
	echo_default "and protected by copyright laws and international treaties."
	echo_default "You may not copy the Software other than as expressly provided"
	echo_default "in this license.  You may not reverse engineer, decompile, or"
	echo_default "disassemble the Software.  If this Software is used within a"
	echo_default "country of the European Union, nothing in this Agreement shall"
	echo_default "be construed as restricting any rights available under the"
	echo_default "European Community Software Directive (91/250/EEC)."
	echo_default ""
	echo_default "Term:  This license is effective until terminated. You may"
	echo_default "terminate it at any time by destroying the Software together"
	echo_default "with all copies in any form.  It will also terminate if you"
	echo_default "fail to comply with any term or condition of this Agreement."
	echo_default "You agree upon such termination to destroy the Software"
	echo_default "together with all copies in any form."
	echo_default ""
	echo_default "LIMITED WARRANTY: This warranty gives you specific legal"
	echo_default "rights and you may also have other rights.  For a period of"
	echo_default "90 days after the date of delivery of the Software to you, as"
	echo_default "evidenced by a copy of your purchase receipt, Alaris warrants"
	echo_default "(i) the Software will perform substantially in accordance with"
	echo_default "the accompanying documentation, and (ii) the media on which the"
	echo_default "Software is furnished will be free from defects in materials"
	echo_default "and workmanship under normal use.  Alaris does not warrant that"
	echo_default "the functions contained in the Software will meet your"
	echo_default "requirements or that the operation of the Software will be"
	echo_default "uninterrupted or error free.  You assume responsibility for"
	echo_default "operation of the Software to achieve your intended results,"
	echo_default "and for the installation, use, and results obtained from the"
	echo_default "Software."
	echo_default ""
	echo_default "Subject to any applicable legislation which prohibits the"
	echo_default "following exclusions, Alaris MAKES NO OTHER WARRANTIES OF ANY"
	echo_default "KIND, EITHER EXPRESS OR IMPLIED, INCLUDING THE IMPLIED"
	echo_default "WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR"
	echo_default "PURPOSE.  Some states and countries, including Australia, do not"
	echo_default "allow the exclusion of implied warranties, or have legislation"
	echo_default "that imposes certain statutory warranties that cannot be"
	echo_default "excluded, so the above exclusion may not apply to you."
	echo_default ""
	echo_default "LIMITATIONS OF REMEDIES:  Subject to any applicable legislation"
	echo_default "which prohibits the following limitations, Alaris' entire"
	echo_default "liability and your exclusive remedy shall be, at Alaris' option"
	echo_default "either (a) the repair or replacement of the Software or any media"
	echo_default "not meeting Alaris' \"Limited Warranty\" that is returned to Alaris"
	echo_default "or your dealer with a copy of your receipt, or (b) the return of"
	echo_default "the price you paid for the Software, provided you have proof of"
	echo_default "the purchase price you paid.  These remedies are not available"
	echo_default "if failure of the Software or media is the result of misuse,"
	echo_default "abuse, or a failure to follow the operating instructions in the"
	echo_default "accompanying written materials."
	echo_default ""
	echo_default "APPLICABLE  LAW:  If the Software was purchased in the United"
	echo_default "States, this Agreement is governed by the laws of the State of"
	echo_default "New York.  If the Software is purchased outside the United States,"
	echo_default "this Agreement is governed by the laws of the country in which"
	echo_default "it was purchased."
	echo_default ""
	echo_default "__________________________________________"
	echo_default "U.S. GOVERNMENT RESTRICTED RIGHTS"
	echo_default "The SOFTWARE and documentation are provided with RESTRICTED RIGHTS."
	echo_default "Use, duplication, or disclosure by the Government is subject to"
	echo_default "restrictions as set forth in subdivision (c)(1)(ii) of The Rights"
	echo_default "in Technical Data and Computer Software clause DFAR 252.227-7013"
	echo_default "or such other applicable government or agency regulation providing"
	echo_default "equivalent protection.  Contractor / manufacturer is"
	echo_default "Kodak Alaris Inc., 2400 Mount Read Blvd., Rochester, New York, 14615."
	echo_default ""
	echo_default ""
	echo_default "******************************"
	echo_default "$dialog v$versioncd"
	echo_default ""
	echo_default -n "Do you agree with the terms of the above software license agreement? (y/N) "
	read_default installOption N Y		# force Yes when silent
	if [ "$installOption" == "N" ]; then
		# User wants to cancel the install.
		print_cancelled_message 10 "license agreement not accepted"
	fi
	# User wants to continue with the installation.
	echo_default ""
}



# see if this distro needs .deb or .rpm packages
#
# on exit:
#    strdistropkg   .deb if a Debian based distro
#                   .rpm if a Fedora based distro
check_distro_pkg()
{
	# see what is on the distro
	dpkgpath=`which dpkg 2>> /dev/null`
	aptgetpath=`which apt-get 2>> /dev/null`
	rpmpath=`which rpm 2>> /dev/null`
	zypperpath=`which zypper 2>> /dev/null`
	yumpath=`which yum 2>> /dev/null`

	# if we have dpkg and apt-get, then it is a Debian distro
	if [ -n "$dpkgpath" ] && [ -n "$aptgetpath" ]; then
		strdistropkg=".deb"
		return
	fi

	# installer and web installer for Fedora
	if [ -n "$rpmpath" ]; then
		if [ -n "$zypperpath" ] || [ -n "$yumpath" ]; then
			strdistropkg=".rpm"
			return
		fi
	fi

	# if we have dpkg and not rpm, then go with Debian
	if [ -n "$dpkgpath" ] && [ -z "$rpmpath" ]; then
		strdistropkg=".deb"
		return
	fi

	# if we have rpm and not dpkg, then go with Fedora
	if [ -z "$rpmpath" ] && [ -z "$dpkgpath" ]; then
		strdistropkg=".rpm"
		return
	fi

	# at this point we have no idea

	# if set on the command-line, then use it
	if [ $usepkgdeb == 1 ]; then
		strdistropkg=".deb"
		return
	fi
	if [ $usepkgrpm == 1 ]; then
		strdistropkg=".rpm"
		return
	fi

	# no on command-line, so ask the user
	echo_default    ""
	echo_default    ""
	echo_default    "******************************"
	echo_default    "Cannot determine which type of install package your operating system needs."
	echo_default    "Your operating system will need either DEB or RPM packages."
	echo_default    "DEB are used on Debian based systems, for example:"
	echo_default    "   Ubuntu, Debian, Pardus, Kylin"
	echo_default    "RPM are used on Fedora based systems, for example:"
	echo_default    "   Fedora, RedHat, SUSE, openSUSE, CentOS, NeoKylin"
	echo_default    ""
	echo_default -n "Does your operating system use DEB packages? (y/N) "
	read_default installOption N
	if [ "$installOption" == "N" ]; then
		echo_default    ""
		echo_default -n "Does your operating system use RPM packages? (y/N) "
		read_default installOption N
		if [ "$installOption" == "N" ]; then
			# User wants to cancel out of the install.
			print_cancelled_message 4 "unknown installer package type"
		else
			strdistropkg=".rpm"
		fi
	else
		strdistropkg=".deb"
	fi
}



# get the information about the distro
#
# on exit:
#    strdistrodesc   the full description of the distro (i.e. pretty name)
#    verdistro       the version of the distro
#    strdistrodist   distro internal name (i.e. ID)
#    strdistro       our name for the distro
check_distro_info()
{
	strdistrodesc=""
	verdistro=""
	strdistrodist=""
	strdistro=""

	# NOTE: SUSE MUST be after openSUSE in the following list
	# NOTE: need 'Red Hat' (with the space) to handle file /etc/redhat-release
	distrodist=( "Ubuntu" "Debian" "Pardus" "Fedora" "openSUSE" "SUSE" "RedHat" "Red Hat" "CentOS" "NeoKylin" "Kylin" "UOS" )

	# os-release seems to be the newer standard over lsb_release, so look for that
	# NOTE: we definitely need this on NeoKylin 7.0 because lsb_release failed
	#       on a clean version of the distro
	if [ -f "/etc/os-release" ]; then
		strdistrodesc=`grep -oP '(?<=^PRETTY_NAME=).+' /etc/os-release | tr -d '"'`
		if [ "$strdistrodesc" == "" ]; then
			strdistrodesc=`grep -oP '(?<=^NAME=).+' /etc/os-release | tr -d '"'`
		fi
		verdistro=`grep -oP '(?<=^VERSION=).+' /etc/os-release | tr -d '"'`
		strdistrodist=`grep -oP '(?<=^ID=).+' /etc/os-release | tr -d '"'`
	fi

	# if we don't have the distro description, then let's try lsb_release
	if [ "$strdistrodesc" == "" ]; then
		lsbrelease=`which lsb_release 2>> /dev/null`
		if [ "$lsbrelease" != "" ]; then
			# get the distro's full description, version and distribution
			strdistrodesc=`lsb_release -d | sed 's/Description: *	*//gI'`
			verdistro=`lsb_release -r | sed 's/Release: *	*//gI'`
			strdistrodist=`lsb_release -i | sed 's/Distributor ID: *	* *//gI'`
		fi
	fi

	# if we still don't have the distro description, then look for SUSE specific file
	if [ "$strdistrodesc" == "" ] && [ -f "/etc/SuSE-release" ]; then
		strdistrodesc=`sed -n 1p /etc/SuSE-release`
		verdistro=`echo $strdistrodesc | sed 's/^.*Server //I' | sed 's/^.*Desktop //I' | sed 's/^.*SUSE //I' | sed 's/ .*$//'`
		strdistrodist="SuSE"
	fi

	# if we still don't have the distro description, then look for Fedora specific file
	if [ "$strdistrodesc" == "" ] && [ -f "/etc/fedora-release" ]; then
		strdistrodesc=`sed -n 1p /etc/fedora-release`
		verdistro=`echo $strdistrodesc | sed 's/^.*release //I' | sed 's/ .*$//'`
		strdistrodist="fedora"
	fi

	# if we still don't have the distro description, then look for RedHat specific file
	if [ "$strdistrodesc" == "" ] && [ -f "/etc/redhat-release" ]; then
		strdistrodesc=`sed -n 1p /etc/redhat-release`
		verdistro=`echo $strdistrodesc | sed 's/^.*release //I' | sed 's/ .*$//'`
		strdistrodist="redhat"
	fi

	# if we still don't have the distro description, then look for Debian specific file
	if [ "$strdistrodesc" == "" ] && [ -f "/etc/debian_version" ]; then
		strdistrodesc="Debian $verdistro"
		verdistro=`sed -n 1p /etc/debian_version`
		strdistrodist="debian"
	fi

	# determine the name we want to use, based on the distro's description
	if [ "$strdistrodesc" != "" ]; then
		for distro in "${distrodist[@]}"
		do
			if [ "`echo $strdistrodesc | grep -i \"$distro\"`" != "" ]; then
				strdistro=$distro

				# if SUSE, then need to know if it is Desktop or Server
				if [ "$strdistro" == "SUSE" ]; then
					if [ "`echo $strdistrodesc | grep -i Desktop`" != "" ]; then
						strdistro="SLED"
					else
						strdistro="SLES"
					fi
				fi
				break
			fi
		done
	fi
}



# see if distro is 32-bit or 64-bit and make sure we have driver package for it
#
# on enter:
#    strdistropkg  package file extension (.deb or .rpm)
#    folowing only used for status messages:
#       strdistrodesc
#       strdistrodist
#       verdistro
#       strdistro
#
# on exit:
#    distro64bit   0 - 32-bit distro
#                  1 - 64-bit distro
#    strdistrodir  x86_64   - 64-bit Intel
#                  i586     - 32-bit Intel
#                  mips64el - 64-bit MIPS
#                  arm64    - 64-bit ARM
#    strdistrobit  result of 'uname -m' (e.g. i686)
#    seLinuxCheck  0 - do not check to see if SELinux is installed
#                  1 - check to see if SELinux is installed
check_distro_bits()
{
	distropkgname32intel=( "i386" "i586" "i686" )
	distropkgname64intel=( "x86_64" "amd64" )
	distropkgname64mips=( "mips64" "mips64el" )
	distropkgname64arm=( "arm64" "aarch64" )

	# determine based on the machine hardware
	strdistrobit=`uname -m`
	strdistrodir=""
	pkgnum=0

	# see if running on 32-bit Intel (we must check all entries)
	pkgfile32intel=""
	for distroname in "${distropkgname32intel[@]}"
	do
		if [ "$strdistrobit" == "$distroname" ]; then
			distro64bit=0
			strdistrodir="i586"
			distropkgnamestr="32intel"
			# do not break; need to check all package names to see if we have it
		fi

		pkgfile=`ls ${mfgdir}_$model*.$distroname$strdistropkg 2>> /dev/null`
		if [ "$pkgfile" != "" ]; then
			pkgnum=$(($pkgnum + 1))
			pkgfile32intel=$pkgfile
			# do not break; need to check all package names to see if we are on that distro
		fi
	done

	# see if running on 64-bit Intel (we must check all entries)
	pkgfile64intel=""
	for distroname in "${distropkgname64intel[@]}"
	do
		if [ "$strdistrobit" == "$distroname" ]; then
			distro64bit=1
			strdistrodir="x86_64"
			distropkgnamestr="64intel"
			# do not break; need to check all package names to see if we have it
		fi

		pkgfile=`ls ${mfgdir}_$model*.$distroname$strdistropkg 2>> /dev/null`
		if [ "$pkgfile" != "" ]; then
			pkgnum=$(($pkgnum + 1))
			pkgfile64intel=$pkgfile
			# do not break; need to check all package names to see if we are on that distro
		fi
	done

	# see if running on 64-bit MIPS (we must check all entries)
	pkgfile64mips=""
	for distroname in "${distropkgname64mips[@]}"
	do
		if [ "$strdistrobit" == "$distroname" ]; then
			distro64bit=1
			strdistrodir="mips64el"
			distropkgnamestr="64mips"
			# do not break; need to check all package names to see if we have it
		fi

		pkgfile=`ls ${mfgdir}_$model*.$distroname$strdistropkg 2>> /dev/null`
		if [ "$pkgfile" != "" ]; then
			pkgnum=$(($pkgnum + 1))
			pkgfile64mips=$pkgfile
			# do not break; need to check all package names to see if we are on that distro
		fi
	done

	# see if running on 64-bit ARM (we must check all entries)
	pkgfile64arm=""
	for distroname in "${distropkgname64arm[@]}"
	do
		if [ "$strdistrobit" == "$distroname" ]; then
			distro64bit=1
			strdistrodir="arm64"
			distropkgnamestr="64arm"
			# do not break; need to check all package names to see if we have it
		fi

		pkgfile=`ls ${mfgdir}_$model*.$distroname$strdistropkg 2>> /dev/null`
		if [ "$pkgfile" != "" ]; then
			pkgnum=$(($pkgnum + 1))
			pkgfile64arm=$pkgfile
			# do not break; need to check all package names to see if we are on that distro
		fi
	done

	# first see if this is a processor we have any chance of supporting
	if [ "$strdistrodir" == "" ]; then
		echo_silent ""
		echo_silent ""
		echo_silent "******************************"
		echo_silent "Your machine/processor is not supported."
		echo_silent "   Detected: $strdistrodesc"
		echo_silent "             ('$strdistrodist' $verdistro - $strdistro $strdistrobit $strdistropkg)"
		exit_and_pause 4
	fi

	# if we found multiple packages, then the installer is bad
	if [ $pkgnum -gt 1 ]; then
		echo_silent ""
		echo_silent ""
		echo_silent "******************************"
		echo_silent "This installation is invalid. Multiple driver packages are not allowed."
		echo_silent "   Detected: $strdistrodesc"
		echo_silent "             ('$strdistrodist' $verdistro - $strdistro $strdistrobit $strdistropkg)"
		exit_and_pause 4
	fi

	# determine which driver package is needed for this distro
	pkgfile=""
	if [ "$distropkgnamestr" == "32intel" ]; then
		pkgfile=$pkgfile32intel
	elif [ "$distropkgnamestr" == "64intel" ]; then
		pkgfile=$pkgfile64intel
	elif [ "$distropkgnamestr" == "64mips" ]; then
		pkgfile=$pkgfile64mips
	elif [ "$distropkgnamestr" == "64arm" ]; then
		pkgfile=$pkgfile64arm
	fi

	# if we don't have the appropriate driver package, then bail
	if [ "$pkgfile" == "" ]; then
		# we didn't find a package for this distro
		
		# try to help the user understand why
		prompt="Your operating system requires a $strdistropkg installation package."
		if [ "$distropkgnamestr" == "32intel" ]; then
			# distro is 32-bit Intel, so see if package is 64-bit Intel or MIPS
			if [ "$pkgfile64intel" != "" ]; then
				prompt="This installer is for 64-bit, but you have a 32-bit operating system."
			elif [ "$pkgfile64mips" != "" ]; then
				prompt="This installer is for 64-bit MIPS, but you have a 32-bit Intel/AMD operating system."
			elif [ "$pkgfile64arm" != "" ]; then
				prompt="This installer is for 64-bit ARM, but you have a 32-bit Intel/AMD operating system."
			fi
		elif [ "$distropkgnamestr" == "64intel" ]; then
			if [ "$pkgfile32intel" != "" ]; then
				prompt="This installer is for 32-bit, but you have a 64-bit operating system."
			elif [ "$pkgfile64mips" != "" ]; then
				prompt="This installer is for 64-bit MIPS, but you have a 64-bit Intel/AMD operating system."
			elif [ "$pkgfile64arm" != "" ]; then
				prompt="This installer is for 64-bit ARM, but you have a 64-bit Intel/AMD operating system."
			fi
		elif [ "$distropkgnamestr" == "64mips" ]; then
			if [ "$pkgfile32intel" != "" ]; then
				prompt="This installer is for 32-bit Intel/AMD, but you have a 64-bit MIPS operating system."
			elif [ "$pkgfile64intel" != "" ]; then
				prompt="This installer is for 64-bit Intel/AMD, but you have a 64-bit MIPS operating system."
			elif [ "$pkgfile64arm" != "" ]; then
				prompt="This installer is for 64-bit ARM, but you have a 64-bit MIPS operating system."
			fi
		elif [ "$distropkgnamestr" == "64arm" ]; then
			if [ "$pkgfile32intel" != "" ]; then
				prompt="This installer is for 32-bit Intel/AMD, but you have a 64-bit ARM operating system."
			elif [ "$pkgfile64intel" != "" ]; then
				prompt="This installer is for 64-bit Intel/AMD, but you have a 64-bit ARM operating system."
			elif [ "$pkgfile64mips" != "" ]; then
				prompt="This installer is for 64-bit MIPS, but you have a 64-bit ARM operating system."
			fi
		fi

		echo_silent ""
		echo_silent ""
		echo_silent "******************************"
		echo_silent "This installation is not compatible with your operating system."
		echo_silent "$prompt"
		echo_silent "   Detected: $strdistrodesc"
		echo_silent "             ('$strdistrodist' $verdistro - $strdistro $strdistrobit $strdistropkg)"
		exit_and_pause 4
	fi

	# for Fedora based systems may have SELinux. we used to only check
	# for this only Fedora/Redhat/CentOS/NeoKylin, and not SUSE/openSUSE.
	# while we haven't seen it on SUSE, that doesn't mean it couldn't be added.
	# this is only used to set secutiry for Hippo, so not real risk if we
	# now check for SUSE as well. this will also cover use for any future
	# Fedora based distro that a user tries to install on
	seLinuxCheck=0
	if [ "$strdistropkg" == ".rpm" ]; then
		seLinuxCheck=1
	fi
}



# see if there is the same or newer version of a file.
# the version must have 3 fields (i.e. x.y.z)
#
# parameters:
#    $1 - file to check
#    $2 - version with 2 dots (i.e. 3 field version: x.y.z)
#    $3 - what to subtract from 1st field (i.e. x) - usualy 0 expect for OpenUSB which is 1
#    $4 - what to subtract from 2nd field (i.e. y) - usualy 0 expect for OpenUSB which is 1
#
# on exit:
#    retval   0 nothing was found
#             1 found something that is the same or higher
check_for_file()
{
	# assume found
	retval=1

	# Split the version into its sections
	IFSprev=$IFS
	IFS="."
	verparts=( $2 )
	IFS=$IFSprev	# put back the old value

	# convert to digits
	ver1=$((${verparts[0]} - $3))
	ver2=$((${verparts[1]} - $4))
	ver3=$((${verparts[2]}))	

	# handle 3rd field being same or higher (libFoundA and libFoundB)
	if [ $ver3 -lt 10 ]; then
		# from number to 9 (e.g. if 1.1.6, then 1.1.6 thru 1.1.9)
		libFound=`find /usr -name "$1\.$ver1\.$ver2\.[$ver3-9]" -print`
		if [ -n "$libFound" ]; then
			return # found something
		fi


		# from 10 to 99 (e.g. if 1.1.6, then 1.1.10 thru 1.1.99)
		libFound=`find /usr -name "$1\.$ver1\.$ver2\.[1-9][0-9]" -print`
		if [ -n "$libFound" ]; then
			return # found something
		fi
	else
		# from number to rest of that tens (e.g. if 1.1.16, then 1.1.16 thru 1.1.19)
		ver3a=$(($ver3 / 10))
		ver3b=$(($ver3 - ($ver3a * 10)))
		libFound=`find /usr -name "$1\.$ver1\.$ver2\.$ver3a[$ver3b-9]" -print`
		if [ -n "$libFound" ]; then
			return # found something
		fi

		# from next tens to 99 (e.g. if 1.1.16, then 1.1.20 thru 1.1.99)
		ver3a=$(($ver3a + 1))
		libFound=`find /usr -name "$1\.$ver1\.$ver2\.[$ver3a-9][0-9]" -print`
		if [ -n "$libFound" ]; then
			return # found something
		fi
	fi

	# handle 2nd field being higher (libFoundC and libFoundD)
	ver2=$(($ver2 + 1)) # if 1.1.16, then 1.2.x OR 1.24.16, then 1.25.x
	if [ $ver2 -lt 10 ]; then
		# from number to 9 (e.g. if 1.1.16, then 1.2.x thru 1.9.x)
		libFound=`find /usr -name "$1\.$ver1\.[$ver2-9]\.*" -print`
		if [ -n "$libFound" ]; then
			return # found something
		fi

		# from 10 to 99 (e.g. if 1.1.16, then 1.10.x thru 1.99.x)
		libFound=`find /usr -name "$1\.$ver1\.[1-9][0-9]\.*" -print`
		if [ -n "$libFound" ]; then
			return # found something
		fi
	else
		# from number to rest of that tens (e.g. if 1.24.16, then 1.25.x thru 1.29.x)
		ver2a=$(($ver2 / 10))
		ver2b=$(($ver2 - ($ver2a * 10)))
		libFound=`find /usr -name "$1\.$ver1\.$ver2a[$ver2b-9]\.*" -print`
		if [ -n "$libFound" ]; then
			return # found something
		fi

		# from next tens to 99 (e.g. if 1.24.16, then 1.30.x thru 1.99.x)
		ver2a=$(($ver2a + 1))
		libFound=`find /usr -name "$1\.$ver1\.[$ver2a-9][0-9]\.*" -print`
		if [ -n "$libFound" ]; then
			return # found something
		fi
	fi

	# handle 1st field being higher (libFoundE and libFoundF)
	ver1=$(($ver1 + 1)) # if 1.1.16, then 2.x.x OR 24.1.16, then 25.x.x
	if [ $ver1 -lt 10 ]; then
		# from number to 9 (e.g. if 1.1.16, then 2.x.x thru 9.x.x)
		libFound=`find /usr -name "$1\.[$ver1-9]\.*\.*" -print`
		if [ -n "$libFound" ]; then
			return # found something
		fi

		# from 10 to 99 (e.g. if 1.1.16, then 10.x.x thru 99.x.x)
		libFound=`find /usr -name "$1\.[1-9][0-9]\.*\.*" -print`
		if [ -n "$libFound" ]; then
			return # found something
		fi
	else
		# from number to rest of that tens (e.g. if 24.1.16, then 25.x.x thru 29.x.x)
		ver1a=$(($ver1 / 10))
		ver1b=$(($ver1 - ($ver1a * 10)))
		libFound=`find /usr -name "$1\.$ver1a[$ver1b-9]\.*\.*" -print`
		if [ -n "$libFound" ]; then
			return # found something
		fi

		# from next tens to 99 (e.g. if 24.1.16, then 30.x.x thru 99.x.x)
		ver1a=$(($ver1a + 1))
		libFound=`find /usr -name "$1\.[$ver1a-9][0-9]\.*\.*" -print`
		if [ -n "$libFound" ]; then
			return # found something
		fi
	fi

	# if here, then nothing was found
	retval=0
}



# see if kernel supports HAL to udev for device communication
#
# on exit:
#    strkernel      the kernel version
#    kernelhal      0 - kernel supports HAL
#                   1 - kernel supports HAL
#    kerneludev     0 - kernel does NOT support udev
#                   1 - kernel supports udev
check_kernel()
{
	strkernel=""
	kernelhal=0
	kerneludev=0

	# Get the 'full' kernel release number
	strfullkernel=$(uname -r)

	# Extract the short kernel version (e.g. "2.6.30"):
	#	- Starting at the left, look for the first character that
	#	  isn't a numeric character or a "." character.
	#	- Once we have that, take the substring leading up to that.
	i=0
	while (( i <= ${#strfullkernel} ))
	do
		chartemp=${strfullkernel:$i:1}
		# Look for numeric character
		chartemp1=`expr match "$chartemp" '\([0-9]\)'`
		# Look for decimal point
		chartemp2=`expr match "$chartemp" '\([.]\)'`
		if [ -z "$chartemp1" ] && [ -z "$chartemp2" ]; then
			# Found a non-numeric character. Pull out the substring.
			strkernel=${strfullkernel:0:$i}
			break
		fi
		((i=i+1))
	done

	# Split the kernel version into its sections
	IFSprev=$IFS
	IFS="."
	kernelparts=( $strkernel )
	IFS=$IFSprev	# put back the old value

	# determine if HAL or udev are expected to be supported
	# less than 2.6.30 requires HAL and the old OpenUSB
	# 2.6.30 and 2.6.31 could have HAL or udev
	# 2.6.32 and up must be udev
	if [ ${kernelparts[0]} -lt 2 ]; then
		kernelhal=1                            # HAL kernel (v1.x or lower)
	elif [ ${kernelparts[0]} -gt 2 ]; then
		kerneludev=1                           # udev kernel (v3.x or greater)
	else
		# is a 2.x kernel
		if [ ${kernelparts[1]} -lt 6 ]; then
			kernelhal=1                        # HAL kernel (v2.0 thru v2.5)
		elif [ ${kernelparts[1]} -gt 6 ]; then
			kerneludev=1                       # udev kernel (v2.7 or greater)
		else
			# is a 2.6.x kernel
			if [ ${kernelparts[2]} -lt 30 ]; then
				kernelhal=1                    # HAL kernel (v2.6.0 thru v2.6.29)
			elif [ ${kernelparts[2]} -lt 32 ]; then
				kernelhal=1                    # HAL kernel (v2.6.30 thru v2.6.31)
				kerneludev=1                   # udev kernel (v2.6.30 thru v2.6.31)
			else
				kerneludev=1                   # udev kernel (v2.6.32 thru v2.6.99)
			fi
		fi
	fi

	# make sure we support this kernel
	min1=2
	min2=6
	min3=24
	if [ "$distropkgnamestr" == "64mips" ]; then
		min1=3
		min2=10
		min3=0
	elif [ "$distropkgnamestr" == "64arm" ]; then
		min1=4
		min2=4
		min3=0
	fi
	if [ ${kernelparts[0]} -gt $min1 ]; then
		# 1st field is higher than our minimum (e.g. v3.x+)
		return
	elif [ ${kernelparts[0]} == $min1 ]; then
		# 1st field is equal to our minimum (e.g. v2.x.x)
		if [ ${kernelparts[1]} -gt $min2 ]; then
			# 2nd field is higher than our minimum (e.g. v2.7.x+)
			return
		elif [ ${kernelparts[1]} == $min2 ]; then
			# 2nd field is equal to our minimum (e.g. v2.6.x)
			if [ ${kernelparts[2]} -gt $min3 ]; then
				# 3rd is higher than our minimum (e.g. v2.6.27+)
				return
			elif [ ${kernelparts[2]} == $min3 ]; then
				# 3rd equal to our minimum (e.g. v2.6.24)
				return
			fi
		fi
	fi

	# if here, then 1st field is lower than the minimum (e.g. v1.x)
	# OR 1st field match minimum and 2nd field is lower than the minimum (e.g. v2.0.x thru v2.5.x)
	# OR 1st & 2nd fiels match minimum and 3rd field is lower than the minimum (e.g. v2.6.0 thru v2.6.23)
	echo_status "v$strkernel"
	echo_silent ""
	echo_silent ""
	echo_silent "******************************"
	echo_silent "This installation is not compatible with your operating system."
	echo_silent "The kernel version must be at least v${min1}.${min2}.${min3}"
	exit_and_pause 25
}



# check to see if mono and mono-winforms are installed
#
# on exit:
#   monoinstalled           0 mono is not installed
#                           1 a valid version of mono is installed (see monover)
#                           2 an unsupported version of mono is installed (see monover)
#   monowinformsinstalled   0 mono-winforms is not installed
#                           1 a valid version of mono-winforms is installed
#                           2 an unsupported version of mono-winforms is installed
#   monover                 blank if no mono installed
#                           otherwise, version of mono that is installed
check_mono_installed()
{
	# assume no mono
	monoinstalled=0
	monowinformsinstalled=0
	monover=""

	# see if mono is even installed
	monojit=`which mono 2>> /dev/null`
	if [ -z "$monojit" ]; then
		return # no mono
	fi

	# we have mono, so get the version
	monover=`$monojit -V | sed -n 1p | sed 's/^.*version //' | sed ' s/ .*$//' 2>> /dev/null`

	# not supported if v1.x, less than v2.4, or v3.x
	if [ "`echo $monover | grep '^1\.[0-9]' 2>> /dev/null`" != "" ]; then
		monoinstalled=2 # mono not supported
		return
	fi
	if [ "`echo $monover | grep '^2\.[0-3]' 2>> /dev/null`" != "" ] && [ "`echo $monover | grep '^2\.[1-3][0-9]' 2>> /dev/null`" == "" ]; then
		monoinstalled=2 # mono not supported
		return
	fi
	if [ "`echo $monover | grep '^3\.[0-9]' 2>> /dev/null`" != "" ]; then
		monoinstalled=2 # mono not supported
		return
	fi

	# mono is installed and is a supported version
	monoinstalled=1

	# since mono is supported, let's see if winforms is installed.
	# we will assume the winforms matches the version of mono.
	monowinforms=`find /usr/lib -name System.Windows.Forms.dll -print 2>> /dev/null`
	if [ -n "$monowinforms" ]; then
		monowinformsinstalled=1		# have winforms
	fi
}

# This function checks if sane is installed
#
# on exit:
#    saneInstalled   0 - XSANE is not installed
#                    1 - XSANE is installed
check_sane_installed()
{
	# Check for folder '/etc/sane.d'
	saneInstalled=0
	if [ -f "/etc/sane.d/dll.conf" ]; then
		saneInstalled=1
	fi
}

# This function checks if XSANE is installed
#
# on exit:
#    xsaneInstalled   0 - XSANE is not installed
#                     1 - XSANE is installed
check_xsane_installed()
{
	# get the path to XSANE
	xsaneapp=`which xsane 2>> /dev/null`
	if [ -n "$xsaneapp" ]; then
		xsaneInstalled=1	# a XSANE is installed
	else
		xsaneInstalled=0
	fi
}



# This function figures out if 'hal' is installed
#
# on enter:
#    $kernelhal     0 if kernel does NOT support HAL; 1 if kernel supports HAL
#
# on exit:
#    halInstalled   0 - HAL is not installed
#                   1 - HAL is installed
#                   2 - HAL is not supported
check_hal_installed()
{
	halInstalled=0

	# if kernel doesn't even support HAL, then don't waste time checking
	if [ $kernelhal != 1 ]; then
		halInstalled=2
		return
	fi

	# What distro are we running on?
	if [ "$strdistropkg" == ".deb" ]; then
		# use dpkg to check for install status.
		# If 'hal' has never been installed, we will get an empty string.
		tmpString1=`$dpkgpath -s hal 2>> /dev/null`
		if [ -n "$tmpString1" ]; then
			# 'hal' is installed, or has been removed from the system.
			# Check if it is currently installed.
			tmpString2=`$dpkgpath -s hal | grep -i 'Status: install' 2>> /dev/null`
			if [ -n "$tmpString2" ]; then
				# Found the string we were looking for. 'hal' is installed.
				halInstalled=1
			fi
		fi
	else
		# For all other distros, use 'rpm -qa'
		tmpString=`rpm -qa | grep 'hal-[0-9]' 2>> /dev/null`
		if [ -n "$tmpString" ]; then
			halInstalled=1
		fi
	fi
}



# This function figures out if 'libudev' is installed
#
# on enter:
#    $kerneludev          0 if kernel does NOT support udev; 1 if kernel supports udev
#
# on exit:
#    udevInstalled        0 - udev is not installed
#                         1 - udev is installed
#                         2 - udev is not supported
#   installlibudev0       need to install 'libudev0'? (0-No; 1-Yes)
#   uninstallbadlibudev0  0 - no action taken
#                         1 - remove a damaged libudev0.so.0.13.1
#   libudevcmd            command to install the libudev0 package
#   libudev0included      0 - libudev0 is not included in this package
#                         1 - libudev0 is included in this package
#   libudev0Installed     0 - libudev0 is not installed
#                         1 - libudev0 is installed
#   libudev1Installed     0 - libudev1 is not installed
#                         1 - libudev1 is installed
check_libudev_installed()
{
	udevInstalled=0
	installlibudev0=0
	uninstallbadlibudev0=0
	libudevcmd=
	libudev0Installed=0
	libudev1Installed=0
	libudev0included=0

	# if kernel doesn't even support udev, then don't waste time checking
	if [ $kerneludev != 1 ]; then
		udevInstalled=2
		return
	fi

	# set a flag to blow away a bad libudev.so.0.13.1.  we're only doing
	# this for RPMs, only for our specific version, and only if we find
	# the file where we know the package installs it, and we can find the
	# libudev0 that came with the distro.  We'll only erase it if GLIBC
	# is flagged (for not being the right version).  if ldd isn't installed,
	# we won't take any action.  this is needed to clean up systems (like
	# CentOS 6) where libudev0 was install but never used, because copy was
	# already living in /lib64 that couldn't be detected, because there's
	# no package for it.
	#
	# Note that if the system has both libudev1 and libudev0, it doesn't
	# matter what we end up doing with libudev0, we'll use libudev1 when
	# it's time to scan...
	if [ "$strdistropkg" == ".rpm" ]; then
		# If we have a libudev0 on this system, then it's installed
		if [ -f /lib64/libudev.so.0 ]; then
			# report that everything we need is installed
			udevInstalled=1
			libudev0Installed=1
			# check for a bad libudev0 installed by us with a previous product...
			if [ -f /usr/lib64/libudev.so.0.13.1 ]; then
				if [[ `ldd -r /usr/lib64/libudev.so.0.13.1 2>&1 | grep GLIBC_` ]]; then
					uninstallbadlibudev0=1
				fi
			fi
			return
		fi
	fi

	# see if there is a libudev0 as part of the installer.
	# this was the case for previous installers when OpenUSB
	# didn't work with libudev1
	tmpString=`ls libudev0*$strdistropkg 2>> /dev/null`
	if [ -n "$tmpString" ]; then
		libudev0included=1
	fi

	# create the command to install libudev0 in case we end up needing to
	if [ "$strdistropkg" == ".deb" ]; then
		libudevcmd="$dpkgpath -i libudev0*.deb"
	else
		libudevcmd="rpm -Uvh --replacefiles --replacepkgs --nodeps libudev0*.rpm"
	fi

	# check based on the distro we running on
	if [ "$strdistropkg" == ".deb" ]; then
		# see if 'libudev0 was ever installed and is currently installed
		tmpString1=`$dpkgpath -s libudev0 2>> /dev/null`
		if [ -n "$tmpString1" ]; then
			tmpString2=`$dpkgpath -s libudev0 | grep -i 'Status: install' 2>> /dev/null`
			if [ -n "$tmpString2" ]; then
				libudev0Installed=1
			fi
		fi

		# see if 'libudev1 was ever installed and is currently installed
		tmpString1=`$dpkgpath -s libudev1 2>> /dev/null`
		if [ -n "$tmpString1" ]; then
			tmpString2=`$dpkgpath -s libudev1 | grep -i 'Status: install' 2>> /dev/null`
			if [ -n "$tmpString2" ]; then
				libudev1Installed=1
			fi
		fi
	else
		# see if 'libudev0' is installed
		tmpString=`rpm -qa | grep 'libudev0' 2>> /dev/null`
		if [ -n "$tmpString" ]; then
			libudev0Installed=1
		fi

		# see if 'libudev1' is installed (e.g. openSUSE 13.1)
		# OR if 'libgudev' is installed (e.g. Fedora 20).
		#    - CentOS 6 has libgudev1 but it contained libudev.so.0
		#    - Fedora 20 has libgudev1, with libudev.so.1
		#    - Fedora 25 has libgudev, with libudev.so.1
		#    The inconsistency of libgudev1 is a problem, but when we added the
		#    libgudev1 check we always considered it to be libudev1. While not
		#    accurate for CentOS, things worked when we installed our libudev0.
		#    When our libudev0 isn't included, we failed on Fedora 25 because
		#    it has just libgudev. Just libgudev is what newer distros are
		#    using. We check for just libgudev and consider it libudev1.
		tmpString1=`rpm -qa | grep 'libudev1' 2>> /dev/null`
		tmpString2=`rpm -qa | grep 'libgudev' 2>> /dev/null`
		if [ -n "$tmpString1" ] || [ -n "$tmpString2" ]; then
			libudev1Installed=1
		fi
	fi

	# if 'libudev0' is included, that means the supplied OpenUSB will
	# only work with libudev0. otherwise we work with either.
	if [ $libudev0included == 1 ]; then
		# we require libudev0, so if it is not installed, we must
		# install it, even if libudev1 is installed
		if [ $libudev0Installed == 0 ]; then
			installlibudev0=1
		else
			udevInstalled=1 # we have the libudev we need
		fi
	else
		# we don't require libudev0, we just need any libudev
		if [ $libudev0Installed == 1 ] || [ $libudev1Installed == 1 ]; then
			udevInstalled=1 # we have a libudev we can use
		fi
	fi
}



# see if OpenUSB is installed already
#
# on exit:
#    openusbInstalled   0 - no OpenUSB installed
#                       1 - some version of OpenUSB is installed
check_openusb_installed()
{
	openusbInstalled=0

	# if there is no OpenUSB at all yet, then we are done
	openusbFound=`find /usr -name libopenusb.so -print`
	if [ -z "$openusbFound" ]; then
		return
	fi

	# an OpenUSB is installed
	openusbInstalled=1
}



# see if TWAIN DSM is installed already
#
# on enter:
#    distro64bit         0 if 32-bit distro; 1 if 64-bit
#
# on exit:
#    twaindsmInstalled   0 - no TWAIN DSM installed
#                        1 - some version of TWAIN DSM is installed
#                        2 - a version is installed, but needs upgrade
check_twaindsm_installed()
{
	twaindsmInstalled=0

	# if there is no TWAIN DSM at all yet, then we are done
	twainDsmFound=`find /usr -name libtwaindsm.so -print`
	if [ -z "$twainDsmFound" ]; then
		return
	fi

	# a TWAIN DSM is installed
	twaindsmInstalled=1

	# If the TWAIN DSM is in the lib64 folder, then we really need to get it
	# in usr/local/lib folder (saw this when SLED 12 was upgraded to SLED 12.2).
	if [ $distro64bit == 1 ] && [ "`echo $twainDsmFound | grep 'lib64' 2>> /dev/null`" != "" ]; then
		twaindsmInstalled=2
	fi
}



# see what OpenUSB goes with this distro and if it needs the included libudev0
#
# on enter:
#    kernelhal        0 if kernel does NOT support HAL; 1 if kernel supports HAL
#    kerneludev       0 if kernel does NOT support udev; 1 if kernel supports udev
#    installlibudev0  need to install 'libudev0'? (0-No; 1-Yes)
#    strdistropkg     ".deb" if Debian distro, otherwise ".rpm"
#
# on exit:
#    installlibudev0  may be updated as needed
#    openusb          same as either $openusbhal or $openusbdev, indicating which
#                        OpenUSB we need to use
#    openusbhal       name of old OpenUSB for HAL systems.
#                     is blank if not in the package
#    openusbudev      name of new OpenUSB for udev systems.
#                     is blank if not in the package
#    openusbhalver    version of the old OpenUSB if in package
#    openusbudevver   version of the new OpenUSB if in package
check_openusb_toinstall()
{
	# figure things out based on whether 'new style' or not
	if [ "$libhasdsmusb" == "1" ]; then
		# TWAIN DSM and OpenUSB are in driver's lib folder, so we will not have an
		# OpenUSB package to install. so let's set our variables accordingly
		openusbhal="__EMBBEDDED__"
		openusbudev="__EMBBEDDED__"
		openusbhalver="???"
		openusbudevver="???"
	else
		# determine which OpenUSBs we have. we know the name for the HAL one
		# and it won't change. so we can look for that. then get all OpenUSB
		# files in the package to see if we have a file with a different
		# name; which would be the name of the new one.
		if [ "$strdistropkg" == ".deb" ]; then
			openusbhal=`ls libopenusb_1.1.0* 2>> /dev/null` # get full name of HAL one
			openusball=`ls libopenusb_* 2>> /dev/null`      # get all the OpenUSBs in the pacakge
		else
			openusbhal=`ls libopenusb-1.1.0* 2>> /dev/null` # get full name of HAL one
			openusball=`ls libopenusb-* 2>> /dev/null`      # get all the OpenUSBs in the pacakge
		fi
		openusbudev=                                        # no udev OpenUSB found yet
		for file in $openusball
		do
			if [ "$file" != "$openusbhal" ]; then
				openusbudev=$file
				break
			fi
		done
		if [ "$strdistropkg" == ".deb" ]; then
			openusbhalver=`echo $openusbhal | sed 's/^libopenusb_//' | sed 's/-.*$//' 2>> /dev/null`
			openusbudevver=`echo $openusbudev | sed 's/^libopenusb_//' | sed 's/-.*$//' 2>> /dev/null`
		else
			openusbhalver=`echo $openusbhal | sed 's/^libopenusb-//' | sed 's/-.*$//' 2>> /dev/null`
			openusbudevver=`echo $openusbudev | sed 's/^libopenusb-//' | sed 's/-.*$//' 2>> /dev/null`
		fi
	fi


	# determine which OpenUSB we will use
	openusb= # assume error
	if [ $kernelhal == 1 ] && [ $kerneludev == 0 ]; then
		# kernel only supports HAL, so use HAL version of OpenUSB
		openusb=$openusbhal
		installlibudev0=0     # make sure we do NOT install libudev0

		# if HAL is not installed, then we have to bail
		if [ $halInstalled == 0 ]; then
			echo_silent ""
			echo_silent ""
			echo_silent "******************************"
			echo_silent "This installer requires the 'hal' package to be installed."
			echo_silent "You will need to re-run this install after you install the 'hal' package."
			exit_and_pause 5
		fi
	elif [ $kernelhal == 0 ] && [ $kerneludev == 1 ]; then
		# kernel only supports udev, so it better be installed or we are installing it
		if [ $udevInstalled == 1 ] || [ $installlibudev0 == 1 ]; then
			# there is, or will be, a udev so use that
			openusb=$openusbudev
		fi
	elif [ $kernelhal == 1 ] && [ $kerneludev == 1 ]; then
		# kernel supports HAL and udev, see which we need to do
		if [ $halInstalled == 1 ] && [ $udevInstalled == 1 ]; then
			# system has both already installed, so go with udev
			openusb=$openusbudev
		elif [ $halInstalled == 1 ] && [ $udevInstalled == 0 ]; then
			# HAL is installed and udev is not, then we need to use HAL
			# because installing udev could cause problems
			openusb=$openusbhal
			installlibudev0=0     # make sure we do NOT install libudev0
		elif [ $halInstalled == 0 ] && [ $udevInstalled == 1 ]; then
			# HAL not supported and udev already installed, so use udev
			openusb=$openusbudev
		else
			# neither are installed, so we are only OK if we are installing udev
			if [ $installlibudev0 == 1 ]; then
				openusb=$openusbudev
			fi
		fi
	else
		# kernel doesn't support HAL or udev (really a programmer error)
		installlibudev0=0     # make sure we do NOT install libudev0
	fi

	# if the embedded one will work, then we are done
	if [ "$openusb" == "__EMBBEDDED__" ]; then
		# clear variable so rest of the installer skips installing OpenUSB
		openusb=""
		return
	fi

	# make sure we have the OpenUSB that we need
	if [ -z "$openusb" ]; then
		echo_silent ""
		echo_silent ""
		echo_silent "******************************"
		echo_silent "This installation is not compatible with your operating system."
		echo_silent "The required OpenUSB is not installed."
		exit_and_pause 23
	fi
}



# see if the distro has everything needed to install libudev0 (must be after check_openusb_toinstall())
#
# on enter:
#    strdistropkg        ".deb" if Debian distro, otherwise ".rpm"
check_libudev0_depends()
{
	# if not installing libudev0, then nothing to check
	if [ $installlibudev0 != 1 ]; then
		return
	fi

	# the only dependency is with the DEB package
	if [ "$strdistropkg" != ".deb" ]; then
		return
	fi

	# this relies on multiarch-support being installed
	multiarch=`dpkg -l | grep multiarch-support 2>> /dev/null`
	if [ "$multiarch" == "" ]; then
		echo_silent ""
		echo_silent ""
		echo_silent "******************************"
		echo_silent "The required multiarch-support package is not installed."
		echo_silent "This package is needed for libudev0."
		echo_silent "You will need to re-run this install after you install the missing package."
		exit_and_pause 24
	fi
}



# see if we need install or upgrade the OpenUSB in this installer
#
# on enter:
#    openusbInstalled   0 if no OpenUSB installed; 1 if some version is installed
#    openusb            same as either $openusbhal or $openusbdev, indicating which
#                          OpenUSB goes with this distro
#
# on exit:
#    installOpenusb     0 - install the OpenUSB that is in this package
#                       1 - do not install OpenUSB from the package
#    removeOpenusb      0 - do not uninstall the currently installed OpenUSB
#                       1 - uninstall the currently installed OpenUSB
check_openusb_needinstall()
{
	installOpenusb=0
	removeOpenusb=0

	# if no OpenUSB to install, then nothing more to do
	if [ "$openusb" == "" ]; then
		return
	fi

	# if there is no OpenUSB installed at all yet, then just install it
	if [ $openusbInstalled == 0 ]; then
		installOpenusb=1 # no OpenUSB installed
		return
	fi

	# an OpenUSB is installed, so determine if it needs to be replaced

	# if we are installing the HAL version of OpenUSB, we must always replace it.
	# This is due to inconsistent versioning, so we can't tell if its old or new.
	if [ "$openusb" == "$openusbhal" ]; then
		removeOpenusb=1   # remove whatever is installed
		installOpenusb=1  # install the one we have
		return
	fi

	# if here, then we are installing the udev version of OpenUSB. only replace it if
	# what we have is newer than what is already installed.
	# while package is 1.1.x, the file is 0.0.x
	check_for_file libopenusb.so $openusbudevver 1 1
	if [ $retval == 0 ]; then
		# didn't find anything the same or newer, so what we have is old
		removeOpenusb=1   # remove the old one that is installed
		installOpenusb=1  # install the one we have
	fi
}



# see if we need install or upgrade the TWAIN DSM in this installer
#
# on enter:
#    twaindsmInstalled   0 if no TWAIN DSM installed; 1 if some version is installed
#    strdistropkg        ".deb" if Debian distro, otherwise ".rpm"
#
# on exit:
#    installTwainDsm     0 - install the TWAIN DSM that is in this package
#                        1 - do not install TWAIN DSM from the package
#    removeTwainDsm      0 - do not uninstall the currently installed TWAIN DSM
#                        1 - uninstall the currently installed TWAIN DSM
check_twaindsm_needinstall()
{
	installTwainDsm=0
	removeTwainDsm=0

	# see if we have a TWAIN DSM pacakge. make sure there is only one.
	twaindsm=`ls twaindsm* 2>> /dev/null`
	twaindsmnum=0
	for file in $twaindsm
	do
		twaindsmnum=$(($twaindsmnum + 1)) # have one
		twaindsmpkg=$file
	done
	if [ $twaindsmnum == 0 ]; then
		return # no TWAIN DSM in the package, so nothing to install
	fi
	if [ $twaindsmnum != 1 ]; then
		echo_silent ""
		echo_silent ""
		echo_silent "******************************"
		echo_silent "Invalid installation package. Too many TWAIN DSM packages found."
		exit_and_pause 8
	fi

	# get the version of the TWAIN DSM that we have. if it doesn't have a version, then
	# it is a release of TWAIN DSM prior to leaving the version in the package name.
	# if that is the case, then assume it is 2.4.2
	if [ "$twaindsmpkg" == "twaindsm$strdistropkg" ]; then
		# no version as part of the package name
		twaindsmver=2.4.2
	else
		if [ "$strdistropkg" == ".deb" ]; then
			twaindsmver=`echo $twaindsmpkg | sed 's/^twaindsm_//' | sed 's/-.*$//' 2>> /dev/null`
		else
			twaindsmver=`echo $twaindsmpkg | sed 's/^twaindsm-//' | sed 's/-.*$//' 2>> /dev/null`
		fi
	fi

	# if there is no TWAIN DSM installed at all yet, then just install it
	if [ $twaindsmInstalled == 0 ]; then
		installTwainDsm=1 # no TWAIN DSM installed
		return
	fi

	# if TWAIN DSM is in the wrong folder, then we have to upgrade
	if [ $twaindsmInstalled == 2 ]; then
		removeTwainDsm=1   # remove whatever is installed
		installTwainDsm=1  # install the one we have
		return
	fi

	# a TWAIN DSM is installed in correct location, so determine if it needs to be replaced
	check_for_file libtwaindsm.so $twaindsmver 0 0
	if [ $retval == 0 ]; then
		# didn't find anything the same or newer, so what we have is old
		removeTwainDsm=1   # remove whatever is installed
		installTwainDsm=1  # install the one we have
	fi
}



# check to see if any scanner from our company is connected and do not continue
# unless nothing is connected
check_scanner_inuse()
{
	# first check lsusb, then check lshal; for each of two possible VIDs
	scannerlist="forceonepassinwhileloop"
	while [ "$scannerlist" != "" ]; do
		# check each VID
		for vid in "${vids[@]}"
		do
			# check lsusb
			scannerlist=`lsusb 2>> /dev/null | grep ": ID $vid" 2>> /dev/null`
			if [ "$scannerlist" != "" ]; then
				break # found a scanner
			fi

			# not found via lsusb, so check lshal. we need to 'fix' the VID
			# because lshal doesn't do leading zeros.
			vidhal=$vid
			if [ "`echo $vid | sed 's/^\(.\).*/\1/'`" == "0" ]; then
				vidhal=`echo $vid | sed 's/^.//'` # strip leading zero
			fi
			scannerlist=`lshal 2>> /dev/null | grep "_${vidhal}_" 2>> /dev/null`
			if [ "$scannerlist" != "" ]; then
				break # found a scanner
			fi
		done

		# if we found anything, then prompt user
		if [ "$scannerlist" != "" ]; then
			echo_default    ""
			echo_default    ""
			echo_default    "******************************"
			echo_default    "Cannot install because a scanner is connected to the PC."
			echo_default    "Please unplug or turn off all scanners."
			echo_default    ""
			echo_default -n "Do you want to retry and then continue with the installation? (Y/n) "
			read_default installOption Y N		# abort if silent
			if [ "$installOption" == "N" ]; then
				# User wants to cancel out of the install.
				print_cancelled_message 6 "scanner connected"
			fi

			# User wants to retry.
		fi
	done
}



# remove/uninstall the given package
function remove_package()
{
	# see if distro has dpkg
	dpkgpath=`which dpkg 2>> /dev/null`
	if [ "$dpkgpath" != "" ]; then
		if [ "`dpkg --get-selections $1 2>>/dev/null | grep ^$1`" != "" ]; then
			echo "Uninstalling package: $1"
			$dpkgpath -P $1
			return
		fi

		# package name in .spec may have underscore, but alien seems to change it to a dash
		pkgname=`echo $1 | sed -e "s/_/-/g"`
		if [ "`dpkg --get-selections $pkgname 2>>/dev/null | grep ^$pkgname`" != "" ]; then
			echo "Uninstalling package: $pkgname"
			$dpkgpath -P $pkgname
			return
		fi
		return
	fi

	# see if distro has rpm
	rpmpath=`which rpm 2>> /dev/null`
	if [ "$rpmpath" != "" ]; then
		if [ "`$rpmpath -qa | grep $1-`" != "" ]; then
			echo "Uninstalling package: $1"
			$rpmpath -e --nodeps $1
		fi
		return
	fi

	echo "Uninstalling did not occur for package: $1"
}



################################################################################
# Initialize installer
################################################################################
# Before we do ANYTHING, make sure they are running as root
if [ `id -u` != "0" ]; then
	echo ""
	echo ""
	echo "******************************"
	echo "You must be logged into the root account (i.e. super user) in order"
	echo "to install this scanner."
	echo ""
	exit 2
fi

# setup install log; this MUST be called before anything else (besides root check)
install_init

# check command line
check_commandline $*



################################################################################
# Introduction
################################################################################
echo_silent
echo_silent "$dialog Installation"
echo_silent
print_license_agreement
echo_status
echo_status "This scanner uses OpenUSB and TWAIN Data Source Manager open source"
echo_status "software, which are already included in this package."
echo_status
echo_status "Source code can be downloaded from:"
echo_status "- OpenUSB: http://openusb.wiki.sourceforge.net"
echo_status "- TWAIN Data Source Manager: http://sourceforge.net/projects/twain-dsm"

# If there is a custom pre install, call it now
if [ -f "custompre.sh" ]; then
	./custompre.sh
fi


################################################################################
# Get distribution information and verify the installer works with it
################################################################################
# see if this distro needs .deb or .rpm packages (sets strdistropkg)
check_distro_pkg

# get the information about the distro (sets strdistrodesc, verdistro, strdistrodist, and strdistro)
check_distro_info

# see if 32 or 64-bit distro and if we have driver package for it
# (sets distro64bit, strdistrodir, strdistrobit, and seLinuxCheck)
# NOTE: must call check_distro_pkg() before this
check_distro_bits




################################################################################
# Display information about the distro and what is installed
################################################################################
echo_status
echo_status "Checking software versions, please wait..."
echo_status    "   Description:         $strdistrodesc"
echo_status    "                        ('$strdistrodist' $verdistro - $strdistro $strdistrobit $strdistropkg)"

# get kernel information (sets strkernel, kernelhal and kerneludev)
echo_status -n "   Kernel:              "
check_kernel # see what the kernel can support (sets kernelhal and kerneludev)
echo_status "v$strkernel"

# Check if SELinux is installed
seLinuxInstalled=0
if [ $seLinuxCheck == 1 ]; then
	echo_status -n "   SELinux:             "
	chconpath=`which chcon 2>> /dev/null`
	if [ -n "$chconpath" ]; then
		seLinuxInstalled=1
		echo_status "installed"
	else
		echo_status "not installed"
	fi
fi

# see if mono and mono-winforms are already installed (sets monoinstalled, monowinformsinstalled and monover)
echo_status -n "   mono:                "
check_mono_installed
if [ $monoinstalled == 0 ]; then
		echo_status "not installed (no TWAIN UI)"
elif [ $monoinstalled == 1 ]; then
		echo_status "v$monover installed"
elif [ $monoinstalled == 2 ]; then
		echo_status "unsupported v$monover installed (no TWAIN UI)"
else
	echo_silent ""
	echo_silent "mono check missing ($monoinstalled)"
	echo_silent ""
	exit_and_pause 99
	return
fi
echo_status -n "   mono-winforms:       "
if [ $monowinformsinstalled == 0 ]; then
		echo_status "not installed (no TWAIN UI)"
elif [ $monowinformsinstalled == 1 ]; then
		echo_status "installed"
elif [ $monowinformsinstalled == 2 ]; then
		echo_status "unsupported version installed (no TWAIN UI)"
else
	echo_silent ""
	echo_silent "mono-winforms check missing ($monowinformsinstalled)"
	echo_silent ""
	exit_and_pause 99
	return
fi

# Check if 'sane' is installed (sets saneInstalled)
echo_status -n "   SANE:                "
check_sane_installed
if [ $saneInstalled == 1 ]; then
	echo_status "installed"
else
	echo_status "not installed"
fi

# Check if 'XSANE' is installed (sets xsaneInstalled)
echo_status -n "   XSANE:               "
check_xsane_installed
if [ $xsaneInstalled == 1 ]; then
	echo_status "installed"
else
	echo_status "not installed (not required)"
fi

# Check if 'hal' is installed (sets halInstalled)
# NOTE: must call check_kernel() before this
echo_status -n "   hal:                 "
check_hal_installed
if [ $halInstalled == 2 ]; then
	echo_status "not supported (will use libudev)"
elif [ $halInstalled == 1 ]; then
	echo_status "installed"
else
	echo_status "not installed"
fi

# check libudev (sets udevInstalled, installlibudev0, libudev0Installed and libudev1Installed)
# NOTE: must call check_kernel() before this
echo_status -n "   libudev0:            "
check_libudev_installed
if [ $udevInstalled == 2 ]; then
	echo_status "not supported"
elif [ $libudev0Installed == 1 ]; then
	if [ $uninstallbadlibudev0 == 1 ]; then
		echo_status "installed (removing unsupported v0.13.1)"
	else
		echo_status "installed"
	fi
else
	if [ $installlibudev0 == 1 ]; then
		echo_status "not installed (using supplied libudev0)"
	else
		echo_status "not installed"
	fi
fi
echo_status -n "   libudev1:            "
if [ $udevInstalled == 2 ]; then
	echo_status "not supported"
elif [ $libudev1Installed == 1 ]; then
	if [ $libudev0included == 1 ]; then
		echo_status "installed (using libudev0)"
	else
		echo_status "installed"
	fi
else
	echo_status "not installed"
fi

# check OpenUSB (sets openusbInstalled)
echo_status -n "   OpenUSB:             "
check_openusb_installed
if [ $openusbInstalled == 1 ]; then
	echo_status "installed"
else
	echo_status "not installed"
fi

# check TWAIN DSM (sets twaindsmInstalled)
echo_status -n "   TWAIN DSM:           "
check_twaindsm_installed
if [ $twaindsmInstalled == 2 ]; then
	echo_status "installed (incorrect location)"
elif [ $twaindsmInstalled == 1 ]; then
	echo_status "installed"
else
	echo_status "not installed"
fi



################################################################################
# Cross check the distro with the files we have to maek sure things are ok
# NOTE: this must be after we know what is installed
################################################################################
check_openusb_toinstall       # see what OpenUSB we have to install (must be after check_kernel() and check_libudev_installed())
check_libudev0_depends        # see if the distro has everything needed to install libudev0 (must be after check_openusb_toinstall())
check_openusb_needinstall     # see if we need to install/upgrade OpenUSB (must be after check_openusb_installed() and check_openusb_toinstall())
check_twaindsm_needinstall    # see if we need to install/upgrade TWAIN DSM (must be after check_twaindsm_installed())

# display the Upgrade Message, if appropriate
if [ $removeOpenusb == 1 ] || [ $removeTwainDsm != 0 ]; then
	# Prompt the user
	echo_default ""
	echo_default ""
	echo_default "******************************"
	echo_default "There are package(s) that are already on your computer that must be"
	echo_default "upgraded in order for this scanner to work. The following is a list"
	echo_default "of the package(s) and the version they will be upgraded to:"
	if [ $removeOpenusb == 1 ]; then
		# upgrading OpenUSB, so list the one we are upgrading to
		if [ "$openusb" == "$openusbhal" ]; then
			echo_default "- OpenUSB v$openusbhalver"
		else
			echo_default "- OpenUSB v$openusbudevver"
		fi
	fi
	if [ $removeTwainDsm != 0 ]; then
		echo_default "- TWAIN Data Source Manager v$twaindsmver"
	fi
	echo_default    ""
	echo_default -n "Do you want to upgrade the above package(s)? (Y/n) "
	read_default installOption Y
	if [ "$installOption" == "N" ]; then
		# User wants to skip the upgrade. Cancel the install.
		print_cancelled_message 11 "do not upgrade packages"
	fi
	# User wants to upgrade or use default which is upgrade
fi



################################################################################
# If no mono or mono-winforms installed, tell user there will be no TWAIN UI
################################################################################
removeUI=0
if [ $monoinstalled != 1 ] || [ $monowinformsinstalled != 1 ]; then
	echo_default    ""
	echo_default    "   NOTE: The TWAIN driver's user interface (i.e. UI) will not be installed."
	echo_default    "         It is only required if your TWAIN application requires it."

	# continue without the UI
	removeUI=1
fi



################################################################################
# If no SANE installed, then confirm that is ok
################################################################################
if [ $saneInstalled == 0 ]; then
	# If the current distro has no 'sane' installed, ask the user if they
	# want to continue without it. If so, they can't scan using xsane.
	echo_default    ""
	echo_default    ""
	echo_default    "******************************"
	echo_default    "The SANE package is not installed on your computer."
	echo_default    "This package is required for SANE applications (e.g. scanimage, XSANE)."
	echo_default    "This package is not required for TWAIN applictions."
	echo_default    "The SANE driver will not be available. After you install the SANE package,"
	echo_default    "you will need to re-run this installer to get the SANE driver."
	echo_default    ""
	echo_default    ""
	echo_default -n "Do you want to continue this installation, without the SANE driver? (y/N) "
	read_default installOption N
	if [ "$installOption" == "N" ] && [ $nosaneok != 1 ]; then
		# User wants to cancel the install.
		print_cancelled_message 14 "SANE not installed"
	fi

	# User wants to continue without sane. Proceed to the next step.
fi



################################################################################
# Display a confirmation message before installing/upgrading any software
################################################################################
echo_default    ""
echo_default    ""
echo_default    "******************************"
echo_default    "The installation is ready to begin (no software was been installed yet)."
echo_default    ""
echo_default    "NOTE: All scanners must be disconnected from your computer until this finishes."
echo_default    ""
echo_default -n "Do you want to continue with the installation? (y/N) "
read_default installOption N Y
if [ "$installOption" == "N" ]; then
	# User wants to cancel out of the install.
	print_cancelled_message 16
fi



################################################################################
# Before installing anything, make sure no scanner is connected to the PC
################################################################################
check_scanner_inuse



################################################################################
# Copy Packages
################################################################################
echo_status    ""
echo_status    ""
echo_status    "******************************"
echo_status    "Copying installation packages to temporary directory: $instdir"
echo_status    "Please wait..."
echo_status    ""

# Copy the packages and any scripts to the temp directory
cp *.rpm "$instdir" 2>> /dev/null
cp *.deb "$instdir" 2>> /dev/null
cp *.sh "$instdir" 2>> /dev/null

currentdir=`pwd`
cd "$instdir"



################################################################################
# ScanTWAIN no longer supported, so remove it if still in package
################################################################################
rm -f scantwain.* 2>> /dev/null



################################################################################
# Remove libudev0...
################################################################################
if [ $uninstallbadlibudev0 == 1 ]; then
	rpm -e libudev0 2>> /dev/null
fi



################################################################################
# Install libudev0 provided with this installer
################################################################################
if [ $installlibudev0 == 1 ]; then
	echo_status ""
	echo_status ""
	echo_status "******************************"
	echo_status "Installing libudev0, please wait..."
	echo_status ""
	eval "$libudevcmd"
	if [ $? -ne 0 ]; then
		echo_silent ""
		echo_silent "libudev0 installation FAILED"
		echo_silent ""
		# when multiarch-support was missing, then package would like it
		# was installed, when it wasn't. so force a clean up to be safe
		if [ "$strdistropkg" == ".deb" ]; then
			$dpkgpath --force-all --purge libudev0 2>> /dev/null
		fi
		exit_and_pause 45
	fi

	# Check if the 'libudev0' install succeeded
	sleep 1
	check_libudev_installed
	if [ $libudev0Installed == 1 ]; then
		echo_status ""
		echo_status "libudev0 installed successfully"
		echo_status ""
	else
		echo_silent ""
		echo_silent "libudev0 installation FAILED"
		echo_silent ""
		echo_silent "The problem could be with your PC's"
		echo_silent "ability to install the package."
		exit_and_pause 42
	fi
fi

# Clean up: done with libudev0 and we only want scanner driver packages left
rm -f libudev0*.* 2>> /dev/null



################################################################################
# Install OpenUSB
################################################################################
# If we need to remove OpenUSB do it now
if [ $removeOpenusb == 1 ]; then
	# Print message
	echo_status    ""
	echo_status    ""
	echo_status    "******************************"
	echo_status    "Removing OpenUSB in order to perform the upgrade, please wait..."
	echo_status    ""

	# Note: ignore errors if we don't find the really old 'openusb'
	if [ "$strdistropkg" == ".deb" ]; then
		$dpkgpath --force-all --purge openusb 2>> /dev/null
		$dpkgpath --force-all --purge libopenusb
	else
		rpm -e --nodeps openusb 2>> /dev/null
		rpm -e --nodeps libopenusb
	fi
fi

# Install OpenUSB, if necessary
if [ $installOpenusb == 1 ]; then
	# Print message
	echo_status    ""
	echo_status    ""
	echo_status    "******************************"
	echo_status    "Installing OpenUSB, please wait..."
	echo_status    ""
	if [ "$strdistropkg" == ".deb" ]; then
		$dpkgpath -i $openusb
		if [ $? -ne 0 ]; then
			echo_silent ""
			echo_silent "OpenUSB installation FAILED"
			echo_silent ""
			exit_and_pause 44
		fi
	else
		rpm -i -v --hash --force --nodeps $openusb
		if [ $? -ne 0 ]; then
			echo_silent ""
			echo_silent "OpenUSB installation FAILED"
			echo_silent ""
			exit_and_pause 44
		fi
	fi
fi
	
# Clean up: done with OpenUSB and we only want scanner driver packages left
rm -f libopenusb*.* 2>> /dev/null



################################################################################
# Install TWAIN DSM
################################################################################
# If we need to remove the TWAIN DSM do it now
if [ $removeTwainDsm != 0 ]; then
	# Print message
	echo_status    ""
	echo_status    ""
	echo_status    "******************************"
	echo_status    "Removing TWAIN Data Source Manager in order to perform the upgrade,"
	echo_status    "please wait..."
	echo_status    ""
	if [ "$strdistropkg" == ".deb" ]; then
		$dpkgpath --force-all --purge twaindsm
	else
		rpm -e --nodeps twaindsm
	fi

	# for added safety, make sure the files are actually gone
	rm -f /usr/local/lib/libtwaindsm*
	rm -f /usr/lib64/libtwaindsm*
fi

# Install the TWAIN DSM, if necessary
if [ $installTwainDsm == 1 ]; then
	# Print message
	echo_status    ""
	echo_status    ""
	echo_status    "******************************"
	echo_status    "Installing TWAIN Data Source Manager, please wait..."
	echo_status    ""
	if [ "$strdistropkg" == ".deb" ]; then
		$dpkgpath -i twaindsm*.deb
		if [ $? -ne 0 ]; then
			echo_silent ""
			echo_silent "TWAIN DSM installation FAILED"
			echo_silent ""
			exit_and_pause 46
		fi
	else
		rpm -Uvh --replacefiles --replacepkgs twaindsm*.rpm
		if [ $? -ne 0 ]; then
			echo_silent ""
			echo_silent "TWAIN DSM installation FAILED"
			echo_silent ""
			exit_and_pause 46
		fi
	fi
fi

# Clean up: done with TWAIN DSM and we only want scanner driver packages left
rm -f twaindsm*.* 2>> /dev/null



################################################################################
# remove any old included flatbed package files
################################################################################
for flatbedpgkname in "${flatbedpgknames[@]}"
do
	remove_package $flatbedpgkname
done



################################################################################
# Install Scanner Packages (i.e. all remaining .deb or .rpm files)
################################################################################
# Print message
echo_status    ""
echo_status    ""
echo_status    "******************************"
echo_status    "Installing scanner packages, please wait..."
echo_status    ""
if [ "$strdistropkg" == ".deb" ]; then
	# Install the remaining DEB packages
	$dpkgpath -i *.deb
	if [ $? -ne 0 ]; then
		echo_silent ""
		echo_silent "Scanner Package installation FAILED"
		echo_silent ""
		exit_and_pause 47
	fi
else
	# Install the remaining RPM packages
	rpm -Uvh --replacepkgs *.rpm
	if [ $? -ne 0 ]; then
		echo_silent ""
		echo_silent "Scanner Package installation FAILED"
		echo_silent ""
		exit_and_pause 47
	fi
fi

# If there is a custom post install, call it now
if [ -f "custompost.sh" ]; then
	./custompost.sh
fi

# Remove the temporary directory
cd "$currentdir"

print_completed_message
