#!/bin/bash
########################################################################
####  Script Name: sm-lib-du-fixes
####  version: 1.4.12
####  Date: 2015-11-16

####  Copyright (C) Harald Hope 2005-2015

####  This program is free software; you can redistribute it and/or modify it under
####  the terms of the GNU General Public License as published by the Free Software
####  Foundation; either version 2 of the License, or (at your option) any later version.

####  This program is distributed in the hope that it will be useful, but WITHOUT
####  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
####  FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

####  Get the full text of the GPL here:
####  http://www.gnu.org/licenses/old-licenses/gpl-2.0.html

####  Script Author: Harald Hope
####  This is a library file for smxi and cannot be run independently

####  Script URL: http://smxi.org/sm/sm-lib-du-fixes
####  Script SVN: http://code.google.com/p/smxi
####  Script Home page: http://techpatterns.com/forums/about736.html
########################################################################

########################################################################
####  FUNCTIONS
########################################################################

###---------------------------------------------------------------------
### du utilities
###---------------------------------------------------------------------

# the hasXX have been set in the caller
check_services()
{
	eval $LOGUS
	local rcconfFeature=0
	
	if [ -z "$hasInsserv" ];then
		if [ -z "$( package_tester 'rcconf' )" ];then
			install_missing_apps 'rcconf' 'feature'
			rcconfFeature=$?
		fi
		if [ "$rcconfFeature" -eq 0 ];then
			# update-rcconf-guide && rcconf
			rcconf
		fi
	elif [ -n "$hasInsserv" -a -n "$hasSysvRcConf"  ];then
		sysv-rc-conf
	else
		echo "${M}This feature not yet available for ${C}insserv${M} running systems without ${C}sysv-rc-conf${M}.${N}"
		print_hec
	fi
	eval $LOGUE
}

# arg: $1 - trap function name
du_trap_handler()
{
	# first echo is to clear the top line
	echo ''
	echo $WLINE
	echo "${W}You exited with ctrl+c or kill, removing holds if needed.${N}"
	if [ -f "$EUKU" ];then
		rm -f $EUKU
	fi
	set_hold_install install
	error_handler 'user-killed-du' "$1"
}

upgrade_package_remove_warning()
{
	eval $LOGUS
	local duInfo='' removedPackages='' removedPackageCount='' removedRawPackages=''
	local newPackages='' newPackageCount='' newPackageMatch='' packageMatchCount=''
	local package='' package2='' packageTemp=''

	# if [ "$APT_TYPE" == 'apt-get' -a "$SYSTEM_BASE" == 'sid' ];then
	if [ "$SYSTEM_BASE" == 'sid' -o "$SYSTEM_BASE" == 'testing' ];then
		# this runs apt-get dist-upgrade unseen on the terminal and answers "no"
		# to "do you want to continue" and stores it's output

		echo "${S}Checking ${C}$APT_TYPE $DU_UPGRADE${S} for packages to be removed...${N}"
		# get the du data for processing
		LC_ALL= LC_CTYPE= LC_MESSAGES= LANG= duInfo="$( echo 'n' | $APT_TYPE $WITHOUT_RECOMMENDS $DU_UPGRADE 2> /dev/null )"

		log_function_data "DU data:\n$duInfo\n"

		# check that there are 0 or some no. of packages 'to remove'.
		# This acts as a check to make sure there is > 0 to remove
		removedPackages=$(echo "$duInfo" | gawk '
		BEGIN { IGNORECASE=1 }
		/.*REMOVED:/ {
			# just to make sure no junk gets included, just the raw data
			while ( getline && !/The following|upgraded|installed/ )
			{
				print $0
			}
		}
		' )

		# slice out the part before the number, if any
		for package in $removedPackages
		do
			# strip out any numbers and data after numbers
			packageTemp=$( echo $package | sed -r 's/([a-z-]{5,})([0-9].*)/\1/' )
			if [ -n "$packageTemp" ];then
				removedRawPackages="$removedRawPackages $packageTemp"
			fi
		done
		# get new package list
		newPackages=$(echo "$duInfo" | gawk '
		BEGIN { IGNORECASE=1 }
		/.*NEW packages.*:/ {
			# just to make sure no junk gets included, just the raw data
			while ( getline && !/The following|upgraded|installed/ )
			{
				print $0
			}
		}
		' )
		# then compare and add to new package list if there's a rough match
		for package in $removedRawPackages
		do
			for package2 in $newPackages
			do
				packageTemp=$( grep "$package" <<< "$package2" )
				if [ -n "$packageTemp" ];then
					newPackageMatch="$newPackageMatch $package2"
				fi
			done
		done
		# then count to see how many, if any
		removedPackageCount=$( wc -w <<< $removedPackages )
		newPackageCount=$( wc -w <<< $newPackages )
		packageMatchCount=$( wc -w <<< $newPackageMatch )

		log_function_data "Packages to be removed:\n$removedPackages\n"
		log_function_data "Packages to be added:\n$newPackages\n"
		log_function_data "Packages remove-added match:\n$newPackageMatch\n"

		# clean the aptitude {a} type gunk out of output display
		removedPackages=$( sed 's/{[a-z]\{1,3\}}//g' <<< $removedPackages )
		newPackages=$( sed 's/{[a-z]\{1,3\}}//g' <<< $newPackages )
		newPackageMatch=$( sed 's/{[a-z]\{1,3\}}//g' <<< $newPackageMatch )

		if [ "$removedPackageCount" -gt 0 ];then
			echo
			echo "${SPACER}${M}The following ${C}$removedPackageCount${M} packages will be removed in your ${C}$DU_UPGRADE${M}:"
			# clean the aptitude {a} type gunk out of output display
			echo "${SPACER}${C}$removedPackages"
			if [ "$newPackageCount" -gt 0 -a "$B_TESTING_1" == 'true' ];then
				echo "${SPACER}${M}The following ${C}$newPackageCount${M} new packages will be added in your ${C}$DU_UPGRADE${M}:"
				echo "${SPACER}${C}$newPackages"
			fi
			if [ "$packageMatchCount" -gt 0 ];then
				if [ "$removedPackageCount" -eq "$packageMatchCount" ];then
					echo "${SPACER}${M}It looks like your removed packages are being upgraded to new versions:"
				else
					echo "${SPACER}${M}It looks like some of these removed packages are being upgraded to new versions:"
				fi
				echo "${SPACER}${C}$newPackageMatch"
			fi
			echo "${SPACER}${S}This is not necessarily a problem. In ${C}Debian $( perl -wp -e '$_ = ucfirst' <<< $SYSTEM_BASE )${S}, packages are often"
			echo "${SPACER}removed and replaced by other packages."
			if [ "$removedPackageCount" -gt 0 -a "$removedPackageCount" -ne "$packageMatchCount" ];then
				echo "${SPACER}But there are also times when updated packages can cause other needed and/or"
				echo "${SPACER}wanted packages to be removed."
				echo "${SPACER}This message simply alerts you that packages will be removed.${N}"
			fi
		else
			echo "${S}No packages will be removed in your ${C}$DU_UPGRADE${S} today. Continuing...${N}"
		fi
		echo $LINE
	fi
	eval $LOGUE
}

###---------------------------------------------------------------------
### Main Dist-Upgrade stuff, pre-du, du, and post-du
###---------------------------------------------------------------------

pre_du_tasks()
{
	eval $LOGMS
	# begin update tasks
	apt_update_handler 'pre-du'

	echo $LINE
	echo "${S}Running assorted tasks to prepare for the system $DU_UPGRADE...${N}"
	launch_function_trigger 'reconfigure-locales'
	kde4_updater
	if [ "$SYSTEM_BASE" != 'stable' -a "$SYSTEM_BASE" != 'etch' ];then
		set_hold_install hold

		# RUN FIRST CRITICAL FIXES. Must run before other fixes to avoid errors in apt
		# generally, these are fixes for kernels, core libs etc, that a new kernel might
		# make needed, like libncurses, libc6, and so on.
		if [ "$DISTRO_LEVEL" -lt 18 ];then
			libc6_fix_1 'pre-du' # ongoing fix, update as needed
		fi
	fi
	# set xorg version pre upgrade, either unset or like 6. or 7. etc
	test_xorg_version pre
	# load the 2009/11 fixes
# 	if [ "$DISTRO_LEVEL" -lt 18 ];then
# 		run_script_import $LIB_2009_FIXES
# 		run_2009_fixes 'pre'
# 	fi
	if [ "$DISTRO_LEVEL" -lt 30 ];then
		run_script_import $LIB_2011_FIXES
		run_2011_fixes 'pre'
	fi

	echo $LINE
	echo "${S}Finished with the pre-upgrade tasks.${N}"

	eval $LOGME
}

# main dist-upgrade/ update etc function
main_upgrade_engine()
{
	eval $LOGMS
	local prefId='du-connection-drop-1'
	local smPref=$( sm_pref_tester $prefId )
	local continue='' repeat='' options='' opt='' ConnectionDropped=''
	local exitStatus=$2 # only for script re-runs, $2 not set first time
	local metaExists=$( package_tester 'linux-image-(2\.6|[3-9])-(sidux-|)' 'wild-full' )
	local currentAptKernelGrub=$( grep -i -o -m1 "$CURRENT_APT_KERNEL" $GRUB_PATH )
	local exitNo='' rebootNo='' rebootText='' rebootTopText=''
	local options="use-install-f $DU_UPGRADE-again check-services continue "
	# these will be passed to the sysv update function
	local hasInsserv=$( check_package_status 'insserv' 'i' )
	local hasSysvRcConf=$( check_package_status 'sysv-rc-conf' 'i' )
	local sysvUpdate='rccconf'
	
	if [ -n "$hasInsserv" -a -n "$hasSysvRcConf" ];then
		sysvUpdate='sysv-rc-conf'
	fi

	# set the trap here
	trap 'du_trap_handler $FUNCNAME' INT TERM

	options="$options exit"
	exitNo=$( echo $options | wc -w )
	# this prints one time, until the first full du is done, will be updated to be more useful.
	# obsolete, but I'll keep it in case I need to flash some version specific du message.
	if [ "$smPref" -eq 0 ];then
		if [ "$DISTRO_LEVEL" -lt 2 ];then
			ConnectionDropped='echo -e "${W}After your $DU_UPGRADE you may lose your network connection.${S}\nIf this happens some parts of the script will not work. To fix this,\nsimply restart the script, and it will restart your connection for you\nif there is no connection present.\n$LINE"'
		fi
	fi

	# only do this part the first time the function runs
	if [ "$1" == "first" ];then
		# run an assortment of pre du stuff, update scripts, keyrings, fixes, etc
		pre_du_tasks
		echo $MBAR
		echo "${M}MAIN $( tr '[a-z]' '[A-Z]' <<< $DU_UPGRADE) HANDLER"
		# print_lib_info "$LIB_DU_FIXES"
		echo $MLINE
		eval $ConnectionDropped
		# note: because the file may not be current or loaded, do not run this if if no warning
		if [ "$B_SKIP_WARNING" != 'true' ];then
			get_configs # print out any keep config stuff
		fi
		upgrade_package_remove_warning
		echo "${S}You are now ready to begin your ${C}$DU_UPGRADE${S}. Make sure that it goes all the"
		echo "through without errors, and of course, always check for packages to be removed."

		# small cosmetic, to avoid printing double line with print-hec
		if [ "$B_SKIP_ENTER" == 'true' ];then
			echo $LINE
		fi
		print_hec
		# all tests already run, so if it's supported and requested, use it
		if [ "$B_USE_DEBDELTA" == 'true' ];then
			run_debdelta
		fi
		$APT_TYPE $WITHOUT_RECOMMENDS $DU_UPGRADE 2>>$LOG_FILE 2>&1
		exitStatus=${PIPESTATUS[0]}
		apt_error_handling du-1 $exitStatus
	fi

	if [ "$exitStatus" -eq 0 ];then
		echo $MLINE
		echo "${M}Your $DU_UPGRADE appears to have completed with no errors."
		echo "${S}You can continue on safely to do the rest of the script now."
		echo
		echo "It does not hurt to run ${C}$DU_UPGRADE-again${S} [option ${C}2${S}] once after a"
		echo "successful $DU_UPGRADE just to make sure things are fine though."
	else
		echo $EBAR
		echo "${E}Your $DU_UPGRADE is reporting errors!"
		echo $EBAR
		echo "${S}Please make sure to do the following to correct the errors reported:"
		echo "${C}$APT_TYPE install -f ${S}[option ${C}1${S}] - Use this first if you got errors!"
		echo
		echo "Run the ${C}$DU_UPGRADE-again${S} [option ${C}2${S}] to make sure the $DU_UPGRADE completes."
		echo "If errors do not get resolved, you'll need to get help from sidux irc or the forums."
		echo
		echo "${M}NOTE: Please run ${C}1${M} and ${C}2${M} as many times as necessary to get rid of the errors."
		echo "${S}Make sure to write down the package error in the $DU_UPGRADE messages."
		echo
		echo "Once you are sure the upgrade is done, you can continue, check services, or exit."
	fi

	# if current kernel was not in grub prior to du, and is in grub post du
	# metapackage users need this alert because otherwise they might not even
	# realize a new kernel installed. Regular kernel users of course don't need
	# to see this information since they know they installed one, and the post kernel
	# install step gives them all the information they need.
	if [ "$currentAptKernelGrub" != "$CURRENT_APT_KERNEL_GRUB" -a -n "$metaExists" -a -n "$currentAptKernelGrub" ];then
		options="$options reboot"
		rebootNo=$( echo $options | wc -w )
		rebootTopText='echo -e "${M}You are using ${C}kernel metapackages${M} and your ${C}$DU_UPGRADE${M} installed a new kernel.\nYour new ${C}$CURRENT_APT_KERNEL${M} kernel will not become active until you reboot.\n$MLINE"'
		rebootText='echo -e "${C}$rebootNo - reboot${M} Reboot into your new ${C}$CURRENT_APT_KERNEL${M} kernel."'
		KERNEL_INSTALL_TO=$CURRENT_APT_KERNEL
	fi
	log_function_data "currentAptKernelGrub: $currentAptKernelGrub"
	log_function_data "CURRENT_APT_KERNEL_GRUB: $CURRENT_APT_KERNEL_GRUB"
	log_function_data "metaExists: $metaExists"
	log_function_data "KERNEL_INSTALL_TO: $KERNEL_INSTALL_TO"

	echo $MLINE
	nonfree_driver_reinstall 'kernel-xorg'
	eval "$rebootTopText"
	echo "${C}1 - use-install-f${S} Use this to try to resolve error in $DU_UPGRADE."
	echo "${C}2 - $DU_UPGRADE-again${S} Run this after correcting an error with ${C}1${S}."
	echo
	echo "${C}3 - check-services${S} Runs ${C}$sysvUpdate${S} to let you turn back off any services that might "
	echo "    have been turned on during the ${C}$DU_UPGRADE${S} (more options in the future)."
	echo
	echo "${C}4 - continue${S} Continue on with script, do this when $DU_UPGRADE is successful."
	eval "$rebootText"

	echo "${C}$exitNo - quit${S} If you need to fix error, you can exit here. In general, please"
	echo "    do not exit unless you need to. The script often runs post $DU_UPGRADE fixes"
	echo "    when you use ${C}continue${S}, and if you exit here, they will not run."
	echo $LINE
	echo -e $SLE
	echo $LINE

	select opt in $options
	do
		eval $LOGME
		case $opt in
			use-install-f)
				$APT_TYPE install $WITHOUT_RECOMMENDS -f 2>>$LOG_FILE 2>&1
				exitStatus=${PIPESTATUS[0]}
				apt_error_handling du-f $exitStatus
				# we will repeat this over and over until it's definitely done
				repeat='true'
				;;
			$DU_UPGRADE-again)
				# all tests already run, so if it's supported and requested, use it
				if [ "$B_USE_DEBDELTA" == 'true' ];then
					run_debdelta
				fi
				$APT_TYPE $WITHOUT_RECOMMENDS $DU_UPGRADE 2>>$LOG_FILE 2>&1
				exitStatus=${PIPESTATUS[0]}
				apt_error_handling du-2 $exitStatus
				repeat='true' # reset so no log if no error
				;;
			check-services)
				check_services
				repeat='true'
				;;
			continue)
				# set some prefs for successful du
				if [ "$smPref" -eq 0 ];then
					set_sticky_prefs $prefId
				fi
				set_sticky_prefs 'd'
				echo "${S}Ok, you are ready to go on now.${N}"
				continue='true'
				;;
			reboot)
				# this is the old/new udev tool for lenny -> squeeze update
				if [ "$B_UDEV_KERNEL26_DU" == 'true' ];then
					udev_kernel_show_post "reboot"
				fi
				set_hold_install install # in case of reboot, make sure to lift hold
				set_sticky_prefs 'd'
				run_script_import $LIB_KERNEL_INSTALL
				reboot_now_question $CURRENT_APT_KERNEL
				;;
			exit)
				# this is the old/new udev tool for lenny -> squeeze update
				if [ "$B_UDEV_KERNEL26_DU" == 'true' ];then
					udev_kernel_show_post
				fi
				set_hold_install install # in case of exit, make sure to lift hold
				set_sticky_prefs 'd'
				print_quit
				;;
			*)
				print_error opt
				repeat='true'
				;;
		esac
		break
	done
	trap - INT TERM
	# run du cleanup etc tasks once user decides to continue, note that
	# script uses the error numbers to determine which message to display on repeat

	if [ "$repeat" == 'true' ];then
		main_upgrade_engine repeat $exitStatus
	elif [ "$continue" == 'true' ];then
		post_du_tasks
	fi
}

run_debdelta()
{
	local exitStatus=0
	
	eval $LOGUS
	echo "${S}Running ${C}debdelta-upgrade${S} now...${N}"
	debdelta-upgrade
	exitStatus="$?"
	#note: exit status 0 is success, but 1 and 2 are ok to have happen
	if [ "$exitStatus" -gt 2 ];then
		error_handler 'debdelta-error' "$FUNCNAME" "$exitStatus"
	else
		echo "${C}debdelta-upgrade${S} appears to have executed successfully. Continuing.${N}"
	fi
	eval $LOGUE
}


## DEBUGGER
#script_debugger 'main_upgrade_engine repeat 1'

# cleanup and set various tweaks post du
# this will only run if user enters the 'continue' option to avoid looping errors
post_du_tasks()
{
	eval $LOGMS
	# set the trap here
	if [ "$SYSTEM_BASE" != 'stable' -a "$SYSTEM_BASE" != 'etch' ];then
		trap 'du_trap_handler $FUNCNAME' INT TERM

		# this is all just debian conversion stuff
		if [ "$B_CON_DEB" == 'true' ];then
			run_script_import $LIB_DISTRO_CONVERSION
			install_window_manager
			install_sidux_components # test to make sure all sidux stuff is installed
			sidux_graphics grub1
		fi

		# load the 2009 fixes
# 		if [ "$DISTRO_LEVEL" -lt 18 ];then
# 			run_2009_fixes 'post'
# 		fi
		if [ "$DISTRO_LEVEL" -lt 30 ];then
		run_script_import $LIB_2011_FIXES
		run_2011_fixes 'post'
	fi
		trap - INT TERM
		## take the package(s) off hold if they were set
		set_hold_install install
		# this is the old/new udev tool for lenny -> squeeze update
		if [ "$B_UDEV_KERNEL26_DU" == 'true' ];then
			udev_kernel_show_post
		fi
	fi
	eval $LOGME
}

###---------------------------------------------------------------------
### permanent du fixes
###---------------------------------------------------------------------

# note, this should in general not be needed, with the exception of cases
# where distro-defaults fails to reset kdm runlevels on kdm reinstall. sidux seems to do this
# but not consistently. I'm not sure about other distros
kdm_3_to_4_fix_1()
{
	eval $LOGUS
	local displayManager=$( get_default_display_manager )
	local prefId='kdm-3-4-fix-1'
	local smPref=$( sm_pref_tester $prefId )
	local defaultRunlevels=''
	local stopLevels='0 1 2 3 4 5 6'
	
	# no point in updating if it's already default debian 2
	if [ -n "$prefId" -a "$displayManager" == 'kdm' -a "$INIT_LEVEL" != 2 ];then
		defaultRunlevels=$( get_display_manager_runlevels )
		if [ -n "$INIT_LEVEL" -a "$INIT_LEVEL" != "$defaultRunlevels" ];then
			echo $LINE
			echo "${S}It looks like your ${C}kdm${S} runlevels got changed by accident. Resetting to default ${C}$INIT_LEVEL${S} now...${N}"
			stopLevels=$( sed "s/$INIT_LEVEL//" <<< $stopLevels )
			update-rc.d -f kdm remove
			update-rc.d kdm start 99 $INIT_LEVEL . stop 01 $stopLevels .
			# this should only get set in case where something happened
			set_sticky_prefs $prefId
		fi
	fi
	eval $LOGUE
}

# test for kde3, if present and kde 4 present, start the procedure
kde4_updater()
{
	eval $LOGUS
	# this needs an off switch for certain cases
	if [ "$B_SKIP_KDE4" != 'true' ];then
		local kateVersionCan=$( check_package_status 'kate' 'c' | cut -d ':' -f 2 | cut -d '.' -f 1 )
		local kwinVersionInst=$( check_package_status 'kwin' 'i' | cut -d ':' -f 2 | cut -d '.' -f 1 )
		local kdmVersionCan=$( check_package_status 'kdm' 'c' | cut -d ':' -f 2 | cut -d '.' -f 1 )
		local kdmVersionInst=$( check_package_status 'kdm' 'i' | cut -d ':' -f 2 | cut -d '.' -f 1 )
		
		## validate
		if [ -z "$kateVersionCan" ];then
			kateVersionCan=0
		fi
		if [ -z "$kwinVersionInst" ];then
			kwinVersionInst=0
		fi
		if [ -z "$kdmVersionCan" ];then
			kdmVersionCan=0
		fi
		if [ -z "$kdmVersionInst" ];then
			kdmVersionInst=0
		fi
		
		log_function_data "kateVersionCan: $kateVersionCan\nkwinVersionInst: $kwinVersionInst\nkdmVersionCan: $kdmVersionCan\nkdmVersionInst: $kdmVersionInst"
		# [ "$B_TESTING_2" == 'true' ] && 
		if [ "$kwinVersionInst" -gt 0 -o "$kdmVersionInst" -gt 0 ];then
			if [ "$kwinVersionInst" -eq 3 -a "$kateVersionCan" -gt 3 ] || [ "$kdmVersionInst" -eq 3 -a "$kdmVersionCan" -gt 3 ];then
				run_script_import $LIB_KDE4_UPDATER
				kde3_to_kde4_updater_main
			fi
		fi
	fi
	eval $LOGUE
}

# this is a permanent fix, since the libc6 stuff mismatches so often
# args: $1 - pre-du or kernel
libc6_fix_1()
{
	eval $LOGUS
	#local libc6Version=$( apt-cache policy libc6 | grep -m 2 ':' | grep -E '2\.[0-4]' )
	# for general users I'll update this if needed now and then, but mostly this is
	# for kernel installs, to avoid the du failure after new kernel
	local prefId='libc6-fix-4'
	local smPref=$( sm_pref_tester $prefId )
	local kernelMessage=' with your new kernel'
	local firmwareLinux='firmware-linux' firmwareLinuxText='firmware-linux/'
	local gccVersions=$( add_gcc_versions ) gccText=''
	# package is not in stable branches yet
	if [ -z "$( check_package_status 'firmware-linux' 'c' )" ];then
		firmwareLinux=''
		firmwareLinuxText=''
	fi
	if [ -n "$gccVersions" ];then
		 gccText='gcc/'
	fi
	
	
	case $1 in
		pre-du)
			kernelMessage=" before you $DU_UPGRADE"
			add_firmware_linux "$firmwareLinux"
			;;
		kernel)
			kernelMessage=' with your new kernel'
			# we want to make sure this is done prior to running locales update if never done
			launch_function_trigger 'reconfigure-locales'
			;;
	esac

 	if [ "$smPref" -eq 0 -o "$1" == 'kernel' ];then
		echo $LINE
		echo "${S}Updating ${C}${firmwareLinuxText}${gccText}libc6/initramfs-tools/locales/tzdata${S} packages to make sure"
		echo "your system will work right$kernelMessage...${N}"
		#echo
		#echo "${M}If ${C}tzdata${M} won't let you pick your right time zone, don't worry,"
		#echo "just select any city if this happens, then the script will let you reconfigure"
		#echo "it after your ${C}$DU_UPGRADE${M} is done. This works fine.${N}"
		package_installer "$firmwareLinux $gccVersions initramfs-tools libc6 libc6-dev locales tzdata util-linux" 'force-always'
		# let's only set this if needed
 		if [ "$smPref" -eq 0 ];then
 			set_sticky_prefs $prefId
 		fi
 	fi
 	eval $LOGUE
 	# I'm putting this in here to make sure it has fired at least once pre kernel install
 	busybox_fix_1
}

# args: $1 - firmwareLinux, if null, it's stable debian, not present
add_firmware_linux()
{
	local prefId='add-firmware-linux-1'
	local smPref=$( sm_pref_tester $prefId )
	
	if [ "$smPref" -eq 0 -a -n "$1" ];then
		echo $LINE
		echo "${S}Adding ${C}$1${S} just in case you need that...${N}"
		package_installer "$1" 'install-missing'
		set_sticky_prefs $prefId
	fi
}
# note: debian has moved to gcc-5 without the .x version, finally
add_gcc_versions()
{
	local isAvailable48=$( check_package_status 'gcc-4.8' 'c' )
	local isAvailable49=$( check_package_status 'gcc-4.9' 'c' )
	local isAvailable5=$( check_package_status 'gcc-5' 'c' )
	local isInstalled48=$( package_tester 'gcc-4.8' )
	local isInstalled49=$( package_tester 'gcc-4.9' )
	local isInstalled5=$( package_tester 'gcc-5' )
	local packageAdd=''
	
	if [ -n "$isAvailable48" -a -z "$isInstalled48" ];then
		packageAdd='gcc-4.8'
	fi
	if [ -n "$isAvailable49" -a -z "$isInstalled49" ];then
		packageAdd="$packageAdd gcc-4.9"
	fi
	if [ -n "$isAvailable5" -a -z "$isInstalled5" ];then
		packageAdd="$packageAdd gcc-5"
	fi
	echo "$packageAdd"
}

busybox_fix_1()
{
	eval $LOGUS
	local prefId='busybox-fix-1'
	local smPref=$( sm_pref_tester $prefId )

	if [ "$smPref" -eq 0 ];then
		echo $LINE
		echo "${S}Running ${C}busybox${S} fix to fix a major bug...${N}"
		package_installer 'busybox' 'install-always'
		set_sticky_prefs $prefId
	fi
	eval $LOGUE
}

# test for udev 0.125 / 14x/15x, if present and kernel < 29, start the procedure
# this tool is for lenny -> squeeze updates
udev_kernel26_update_handler()
{
	eval $LOGUS
	local prefId='udev-kernel26-fix-1'
	local smPref=$( sm_pref_tester $prefId )

	# this needs an off switch for current squeeze and newer since they already have this fine
	if [ "$smPref" -eq 0 ];then
		# lenny: 0.125-23 / squeeze-sid: 150-2, adding : test in case they change it, again...
		local udevVersionCan=$( check_package_status 'udev' 'c' | cut -d ':' -f 2 | sed 's/0\.//' | cut -d '-' -f 1 )
		local udevVersionInst=$( check_package_status 'udev' 'i' | cut -d ':' -f 2 | sed 's/0\.//' | cut -d '-' -f 1 )
		
		## validate
		if [ -z "$udevVersionCan" ];then
			udevVersionCan=0
		fi
		if [ -z "$udevVersionInst" ];then
			udevVersionInst=0
		fi
		
		log_function_data "udevVersionCan: $udevVersionCan\nudevVersionInst: $udevVersionInst"
		# don't run this if no udev is installed, then this doesn't matter
		case $KERNEL_BASE in
			2.6)
				if [ "$KERNEL_MATH" -lt 30 -a "$udevVersionCan" -gt 140 -a "$udevVersionInst" -lt 130 -a "$udevVersionInst" -gt 0 ];then
					udev_kernel_updater_main
				fi
				# this should always run until the safe udev + new kernel is installed
				if [ "$KERNEL_MATH" -gt 28 -a "$udevVersionInst" -gt 140 ];then
					set_sticky_prefs $prefId
				fi
				;;
		esac
		
	fi
	eval $LOGUE
}

udev_kernel_updater_main()
{
	eval $LOGUS
	
	local options="continue-kernel-install-$DU_UPGRADE continue-kernel-install-reboot quit" 
	local opt='' repeat=''
	local etcUdevKU='/etc/udev/kernel-upgrade'
	
	echo $MLINE
	echo "${M}ALERT: The new ${C}udev${M} version ${C}$udevVersionCan${M} requires special handling, "
	echo "when you are running kernel ${C}2.6.$KERNEL_MATH${M}. ${C}$SCRIPT_NAME${M} can handle most"
	echo "of the process for you, but you must do the following:"
	
	echo $LINE
	echo "${C}1${S} - Install a new kernel > 2.6.30${S} in the following kernel install section."
	echo "${C}2${S} - Run the complete ${C}$DU_UPGRADE${S} all the way to the end."
	echo "${C}3${S} - Reinstall your non free video driver if required (only nvidia supports installing to new kernel)."
	echo "${C}4${S} - Reboot. This is very important. The new ${C}udev $udevVersionCan${S} will NOT work with your old kernel."
	echo
	echo "If you want to do this procedure differently, you can also do it this way:"
	echo "${C}1${S} - Install a new kernel > ${C}2.6.30${S} in the following kernel install section."
	echo "${C}2${S} - Reboot, then do your ${C}$DU_UPGRADE${S} (make sure you are using full-upgrade/dist-upgrade here."
	if [ "$DEFAULT_KERNEL" == 'no-kernel' ];then
		echo "${M}ALERT: You have manually set your kernel type to ${C}no-kernel${M}: Please"
		echo "Update your kernel manually before continuing or you will have upgrade problems."
	fi
	echo $LINE
	echo "${C}1 - continue-kernel-install-$DU_UPGRADE${S} Continue, install new kernel, run ${C}$DU_UPGRADE${S}, then reboot."
	echo
	echo "${C}2 - continue-kernel-install-reboot${S} Continue, install new kernel, reboot, then do the ${C}$DU_UPGRADE${S}."
	eval "$rebootText"

	echo "${C}3 - quit${S} I want to handle this manually, or get more information."
	echo $LINE
	echo -e $SLE
	echo $LINE

	select opt in $options
	do
		eval $LOGUE
		log_function_data "$opt"
		case $opt in
			continue-kernel-install-$DU_UPGRADE)
				# set global test flag to true, this enables kernel installer and other tests/fixes
				B_UDEV_KERNEL26='true'
				B_UDEV_KERNEL26_DU='true'
				B_SKIP_KERNEL='false'
				if [ ! -f "$EUKU" ];then
					touch $EUKU
				fi
				;;
			continue-kernel-install-reboot)
				# set global test flag to true, this enables kernel installer and other tests/fixes
				B_UDEV_KERNEL26='true'
				B_SKIP_KERNEL='false'
				;;
			quit)
				print_quit
				;;
			*)
				print_error opt
				repeat='true'
				;;
		esac
		break
	done

	if [ "$repeat" == 'true' ];then
		udev_kernel_updater_main
	fi
}

# args: $1 - reboot (optional)
udev_kernel_show_post()
{
	eval $LOGUS

	local isNvidia=$( get_gfx_driver_info 'nvidia' )
	
	# remove this first in case of user ctrl c exit, also found in du trap handler
	if [ -f "$EUKU" ];then
		rm -f $EUKU
	fi
	if [ "$1" != 'reboot' ];then
		echo $WLINE
		echo "${M}Remember, you MUST reboot after you have finished with ${C}$SCRIPT_NAME${M}!!"
		if [ -n "$isNvidia" ];then
			echo "${S}Proceed to graphics driver install if you need to re-install your"
			echo "nVidia driver, then reboot.${N}"
		fi
		echo
		echo "${M}Failure to reboot after you are finished will make your system inoperable!!${N}"
		B_UDEV_KERNEL26_DU='false'
		print_hec
	fi

	eval $LOGUE
}

nvidia_sse_alert()
{
	eval $LOGUS
	local isSse=$( grep -io 'sse' /proc/cpuinfo )
	# for some reason using \s* fails randomly for space test
	# local isNvidia=$( grep -Eio 'Driver.*"nvidia"' $X_ORG_PATH | cut -d '"' -f 2  )
	# I'm going to test for nvidia alone in the lspci output in case they are running nv
	 local isNvidia=$( lspci | grep -E '([[:space:VGA[[:space:]]|Display controller|3D controller)' | \
	 grep -i 'nvidia' )

	if [ -z "$isSse" -a -n "$isNvidia" ];then
		echo $MLINE
		echo "${M}ALERT: In the latest ${C}nVidia${M} ${C}169.xx${M} and greater drivers, "
		echo "${C}OpenGL${M} requires ${C}CPUs with SSE${M} to run."
		echo
		echo "${W}Your${C}$CPU_NAME${W} does ${C}NOT${W} support ${C}SSE."
		echo $MLINE
		echo "${S}What does this mean? It means with new drivers you will not have 3d support."
		echo "The 100 series drivers do work, but cannot be installed on 2.6.28 or newer kernels."
		echo
		echo "${S}Only drivers of series ${C}169/96/71${S} or newer work on ${C}2.6.26${S} and later kernels."
		echo "For now, this leaves you with only these choices:"
		echo "${C}1 - ${S}Stay with the latest ${C}2.6.27${S} kernel and use the ${C}100.xx${S} drivers."
		echo "    You must install these drivers directly with sgfxi, like this: ${C}sgfxi -co 100.14.19"
		echo "${C}2 - ${S}Forget about 3d and just use the 2d part of the driver, or run the legacy ${C}7xxx${S} drivers."
		echo "${C}3 - ${S}Use the ${C}xorg nv${S} drivers instead, which aren't very good."
		echo "${C}4 - ${S}Use the ${C}xorg nouveau${S} drivers instead, and see if they work for you."
		echo "${C}5 - ${S}Get an old used ${C}ATI 7/8/9xxx${S} card that has fine working ${C}xorg drivers."

		log_function_data "Is sse cpu and nvidia system."
		print_hec
	fi
	eval $LOGUE
}
# nvidia_sse_alert
###---------------------------------------------------------------------
### various du fixes
### NOTE: these fixes are contined in sm-lib-20xx-fixes files
###---------------------------------------------------------------------

# HANDLED BY EXTERNAL LIBRARY FILES sm-lib-20xx-fixes

###---------------------------------------------------------------------
###
###---------------------------------------------------------------------

###---------------------------------------------------------------------
###
###---------------------------------------------------------------------


###**EOF**###


syntax highlighted by Code2HTML, v. 0.9.1