#!/bin/bash
########################################################################
####  Script Name: sm-lib-distro-conversion
####  version: 3.3.17
####  Date: 2014-03-29

####  Copyright (C) Harald Hope 2005-2014
####  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-distro-conversion
####  Script SVN: http://code.google.com/p/smxi
####  Script Home page: http://techpatterns.com/forums/about736.html
########################################################################

B_OFFER_LIQUORIX_KERNELS='false'

# will remove flag files if user exits early
# args: $1 - FUNCNAME
conversion_trap_handler()
{
	# first echo is to clear the top line
	echo ''
	echo $WLINE
	echo "${W}You exited before completing the conversion process."
	echo "Removing all conversion identifier files and exiting now...${N}"
	rm -f $SMDV  $SMDL
	error_handler 'user-killed-conversion' "$1"
}

# args: $1 - repeat
check_debian()
{
	eval $LOGMS
	trap 'conversion_trap_handler $FUNCNAME' INT TERM EXIT
	local opt='' options='' repeat='' optionSet='debian'
	local conversionOptions='aptosid-sources'
	local quitNu='' mepisId='' bSkipQuestion='true'
	local altText1="${S}Adding ${C}Aptosid sources${S} let you run Aptosid kernels."
	
	# dump the ats stuff
	conversionOptions=''
	altText1=""
	
	case $SYSTEM_BASE in
		stable|squeeze|lenny|etch)
			# have to use this for wild card mepis string, mepis-8.x...
			case $DISTRO in
				mepis*)
					mepisId=' Mepis'
					;;
			esac
			conversionOptions=''
			#altText1="${M}It is not safe to run aptosid sources with your${C}$mepisId Debian Stable${M} system\nso those options are not being offered to you, sorry."
			altText1=""
			optionSet='stable'
			;;
		*)
			if [ "$BITS" == '64' -o "$( check_pae_exists )" == 'true' ];then 
				B_OFFER_LIQUORIX_KERNELS='true'
			fi
			;;
	esac

	if [ "$DISTRO" == 'antix' ];then
		conversionOptions='antix-sid ' # removed: antix-sid-aptosid
		altText1="${M}Here are your options for your Anti-X system:"
		optionSet='antix'
		bSkipQuestion='false'
# 	elif [ "$DISTRO" == 'aptosid' ];then
# 		conversionOptions=''
# 		altText1=''
# 		optionSet='aptosid'
	fi
	options="continue-no-change $conversionOptions quit"
	quitNu=$( wc -w <<< $options )

	print_lib_info $LIB_DISTRO_CONVERSION
	echo $MBAR
	echo "${M}You appear to be using Debian or a Debian derived distro based on ${C}Debian $SYSTEM_BASE${S}."
	echo "${S}If you want to run ${C}$SCRIPT_NAME${S}, please select from the following option(s)."
	echo "You will be asked a series of initial setup questions. You will only be asked these once."
	echo
	echo "${W}There are no guarantees, as is the case with all ${C}GPL${W} code."
	echo "${S}However, based on most user's experience, your results should be fine.${S}"
	echo -e "$altText1"
	echo $LINE
	echo "${C}1${S} - ${C}continue-no-change${S} Runs ${C}$SCRIPT_NAME${S} without changing anything."
	echo "    Only ${C}$SCRIPT_NAME${S} fixes will run, and you can use the other script options too."

	case "$optionSet" in
		antix)
			echo "${C}2${S} - ${C}antix-sid${S} Adds sid sources to your apt repos, otherwise no change."
			echo "    This lets you for example run Debian Sid kernels."
# 			echo "${C}3${S} - ${C}antix-sid-aptosid${S} Adds sid sources and aptosid sources, no aptosid package installs."
# 			echo "${C}4${S} - ${C}antix-aptosid-packages${S} Adds sid sources/aptosid sources, installs core aptosid packages."
# 			echo "    ${M}NOTE: This will not ${C}convert${M} your system to aptosid, just install some packages."
# 			echo "    ${M}You must not exit ${C}$SCRIPT_NAME${M} until the entire process is completed."
			;;
# 		aptosid)
# 			echo "    ${M}Please note: ${C}Aptosid${M} users: ${C}$SCRIPT_NAME${M} now will treat"
# 			echo "    Aptosid as a standard Debian derived distro."
# 			echo
# 			echo "    Not all the old distro specific features will be working the way they used"
# 			echo "    to when ${C}sidux${M} existed."
# 			;;
		debian)
# 			echo "${C}2${S} - ${C}aptosid-sources${S} Adds aptosid sources to your apt repos, otherwise no change."
# 			echo "    This lets you for example run Debian Sid with aptosid fixes and kernels."
# 			echo "${C}3${S} - ${C}aptosid-packages${S} Will add aptosid sources and install core aptosid packages."
# 			echo "    ${M}NOTE: This will not ${C}convert${M} your system to aptosid, just install some packages."
# 			echo "    ${M}You must not exit ${C}$SCRIPT_NAME${M} until the entire process is completed."
			:
			;;
	esac

	echo "${C}$quitNu${S} - ${C}quit${S} I don't want to proceed, I'm exiting now."
	echo $LINE
	echo $SLE
	echo $LINE

	options="continue-no-change $conversionOptions quit"
	select opt in $options
	do
		case $opt in
			continue-no-change)
				# tweak_antix_vb_source # only runs if detected so fine for general use
				update_smxi_data
				echo "${S}Ok, you can use ${C}$SCRIPT_NAME${S} with no changes to your system, proceed.${N}"
				trap - INT TERM EXIT
				;;
			antix-sid)
				update_smxi_data
				tweak_antix_sources
				update_to_new_sources 'debian-sid'
				antix_fix_1
				trap - INT TERM EXIT
				;;
			antix-sid-aptosid)
				update_smxi_data
				tweak_antix_sources
				update_to_new_sources 'debian-sid'
				update_to_new_sources 'aptosid'
				run_script_import $LIB_MISC_TWEAKS
				set_default_system_kernel 'conversion'
				antix_fix_1
				trap - INT TERM EXIT
				;;
			antix-aptosid-packages)
				update_smxi_data
				tweak_antix_sources
				update_to_new_sources 'debian-sid'
				update_to_new_sources 'aptosid'
				run_script_import $LIB_MISC_TWEAKS
				set_default_system_kernel 'conversion'
				antix_fix_1
				print_conversion_information
				B_CON_DEB='true'
				trap - INT TERM EXIT
				;;
			aptosid-sources)
				update_smxi_data
				update_to_new_sources 'aptosid'
				run_script_import $LIB_MISC_TWEAKS
				set_default_system_kernel 'conversion'
				trap - INT TERM EXIT
				;;
			aptosid-packages)
				update_smxi_data
				update_to_new_sources 'aptosid'
				run_script_import $LIB_MISC_TWEAKS
				set_default_system_kernel 'conversion'
				print_conversion_information
				B_CON_DEB='true'
				trap - INT TERM EXIT
				;;
			quit)
				print_quit
				;;
			*)
				print_error opt
				repeat='true'
				;;
		esac
		break
	done
	eval $LOGME
	if [ "$repeat" == 'true' ];then
		check_debian 'repeat'
	fi
}

print_conversion_information()
{
	eval $LOGUS
	echo $MLINE
	echo "${C}$SCRIPT_NAME${M} will now proceed to the $DU_UPGRADE, which will update your system to current."
	echo "Do not quit the script until the $DU_UPGRADE and post $DU_UPGRADE aptosid package"
	echo "install is completed!"
	echo ""
	print_hec
	eval $LOGUE
}

install_window_manager()
{
	eval $LOGUS
	echo $MBAR
	echo "${M}Window manager install process"
	echo $LINE
	echo "${S}After the aptosid components are installed, please continue on to the"
	echo "${C}Package Install${S} section which will come next, in ${C}Post $DU_UPGRADE${S}."
	echo "Choose the ${C}display manager${S} option, then first install xorg, then your preferred."
	echo "display manager. For older installs I recommend ${C}xfce${S} or ${C}fvwm crystal${S}.${N}"
	print_hec
	set_sticky_prefs debian-to-aptosid-wm-1
	eval $LOGUE
}

install_aptosid_components()
{
	eval $LOGPS
	local prefId='install-aptosid-packages-1'
	local smPref=$( sm_pref_tester $prefId )
	local aptosidPackages='apt-conf-aptosid configure-cups configure-dsl configure-ndiswrapper ceni deborphan distro-defaults gfxboot-theme-aptosid gpm aptosid-irc aptosid-kernelhacking aptosid-keyrings aptosid-scripts udev-config-aptosid wodim'
	# grub-gfxboot
	local i='' installedPackage=''

	if [ "$smPref" -eq 0 ];then
		echo $MBAR
		echo "${M}SIDUX PACKAGE INSTALL"
		echo $LINE
		echo "${S}This will double check your system to make sure you have the main"
		echo "${C}aptosid${S} packages that you need for basic aptosid functionality."
		echo
		echo "Please read each item and tell ${C}apt${S} if you want it or not by"
		echo "answering ${C}y${S} or ${C}n${S} to $APT_TYPE install questions. For example, "
		echo "if you don't use ${C}ndiswrapper${S} or ${C}dsl${S}, answer ${C}n${S} to those packages.${N}"

		print_hec
		echo "${S}Checking for and installing missing ${C}aptosid${S} packages now...${N}"
		for i in $aptosidPackages
		do
			package_installer "$1" 'install-missing'
		done
		echo "${S}Finished installing ${C}aptosid${S} packages.${N}"
		set_sticky_prefs $prefId
	fi
	eval $LOGPE
}

# this one needs work, not currently functioning
aptosid_graphics()
{
	:
}
aptosid_graphics_legacy()
{
	local prefId='aptosid-graphics-2'
	local smPref=$( sm_pref_tester $prefId ) #$GRUB_PATH
	local OldGrub=$( awk -F= '/^# groot/{print $2}' /boot/grub/menu.lst | sed -r 's/\((.*)\)/\1/' )
	local bm='/boot/message'

	if [ "$1" == 'grub1' -a "$smPref" -eq 0 ];then
		echo $LINE
		echo "${S}Running ${C}aptosid grub${S} fix...${N}"
		# make a copy of old penguin graphic
		if [ -f $bm.hd -a "$DISTRO_LEVEL" -lt 5 ];then
			cp $bm.hd $bm.hd-bu
		fi
		# check for old physical file, move to renamed
		if [ -f $bm ];then
			mv -f $bm $bm.preaptosid
		fi
		# package_installer 'aptosid-graphics aptosid-graphics-common' 'install-always' '--reinstall'

		# force link to file
		if [ -L $bm -o ! -e $bm ];then
			ln -fs message.hd $bm
		else
			echo "${E}No grub graphics file was found. Sorry, script cannot resolve this for you.${N}"
		fi
		echo "${S}Running  ${C}grub-install${S} first time to update grub....${N}"
		grub-install --recheck --no-floppy $OldGrub
		echo "${S}Running  ${C}grub-install${S} again...${N}"
		grub-install --recheck --no-floppy $OldGrub
		echo "${S}Finished with ${C}aptosid grub${S} update and graphics reinstall.${N}"
		set_sticky_prefs $prefId
	fi
}

###---------------------------------------------------------------------
### conversion utilities
###---------------------------------------------------------------------

offer_liquorix_kernel()
{
	eval $LOGUS
	local opt='' options='yes-add-liquorix-sources continue-without-adding-liquorix'
	local repeat='false'
	
	echo $MLINE
	echo "${M}Add ${C}Liquorix${M} Kernel Sources?"
	echo $MLINE
	echo "${S}Selecting ${C}yes-add-liquorix-sources${S} will add ${C}Liquorix${S} kernel apt repositories"
	echo "to your system, after which you will be able to install them in ${C}$SCRIPT_NAME${S}'s"
	echo "${C}Advanced Kernel Install${S} options, or make it your system default in the"
	echo "${C}Miscellaneous Tweaks${S} section."
	echo 
	echo "${C}Liquorix${S} kernels${S} are popular desktop optimized performance kernels."
	echo $LINE
	echo $SLE
	echo $LINE
	select opt in $options
	do
		case $opt in
			yes-add-liquorix-sources)
				run_script_import $LIB_KERNEL
				add_alternate_kernels_sources "liquorix"
				run_script_import $LIB_MISC_TWEAKS
				set_default_system_kernel 'conversion'
				;;
			continue-without-adding-liquorix)
				echo "${S}OK, moving along without adding Liquorix sources...${N}"
				;;
			*)
				print_error opt
				repeat='true'
				;;
		esac
		break
	done
	eval $LOGUE
	if [ "$repeat" == 'true' ];then
		offer_liquorix_kernel
	fi
}

update_smxi_data()
{
	eval $LOGPS
	run_script_import $LIB_MISC_TWEAKS
	if [ "$B_OFFER_LIQUORIX_KERNELS" == 'true' ];then
		offer_liquorix_kernel
	fi
	# this tests for presence of aptitude, and only offers itself if user has aptitude installed
	set_apt_type 'conversion'
	set_upgrade_type 'conversion'
	distro_number_calculator
	set_distro_version # just in case user exits, we'll still have the level set
	eval $LOGPE
}

set_distro_version()
{
	eval $LOGPS
	local repeat='' opt=''

	local distros='
	debian-stable
	debian-testing
	debian-sid
	debian-other
	'

	if [ ! -f $SMDV -a ! -f $EAX ];then
		echo $MLINE
		echo "${M}Set Distro Version Data"
		echo $MLINE
		echo "${S}The folowing Debian versions have been tested at some point, and have worked."
		echo "Since it is very hard to detect for them reliably, please select the distro"
		echo "identier that best fits your system and we can proceed."
		echo "${C}$SCRIPT_NAME ${M}detects your system base as: ${C}Debian $SYSTEM_BASE${S}"
		echo
		echo "This is just an internal ${C}$SCRIPT_NAME${S} script identifier, and will not affect your system."
		echo "${C}$SCRIPT_NAME${S} may use this information to determine which fixes to apply in the future."
		echo
		echo "If you pick ${C}debian-other${S} and ${C}$SCRIPT_NAME${S} works, please notify"
		echo "the script author with the distro so he can add that distro identifier, thanks."
		echo $LINE
		echo $SLE
		echo $LINE
		select opt in $distros
		do
			case $opt in
				debian-stable|debian-testing|debian-sid|debian-other)
					write_smdv_file "$opt"
					;;
				*)
					print_error opt
					repeat='true'
					;;
			esac
			break
		done
		eval $LOGPE
		if [ "$repeat" == 'true' ];then
			set_distro_version
		fi
	elif [ ! -f $SMDV -a -f $EAX ];then
		write_smdv_file 'anti-x'
		eval $LOGPE
	fi
}

# args: $1 which smdv type
write_smdv_file()
{
	eval $LOGUS
	local timeStamp=$( date +%Y%m%d ) fullIdString=''

	fullIdString="$1:sc:$timeStamp"
	echo $fullIdString > $SMDV
	DISTRO_VERSION=$fullIdString
	eval $LOGUE
}

# this is going to just make a rough working guess to avoid running ALL fixes
# data: 2008-1:10;etc To simplify, I'll make each date 3 version back
# arrangement: <year>:<last quarter month number>:<distro equivalent>
distro_number_calculator()
{
	eval $LOGUS
	local year=$( date +%Y )
	local month=$( date +%m )
	local distroYear='' distroMonth='' distroLevel='' item='' assembled=''
	# assume system is reasonably up to date for fixes
	local distroLevels='
	2010:09:20
	2010:12:21
	2011:03:22
	2011:06:23
	2011:09:24
	2011:12:25
	2012:03:26
	2012:06:27
	2012:09:28
	2012:12:29
	2013:03:30
	2013:06:31
	2013:09:32
	2013:12:33
	2014:03:34
	2014:06:35
	2014:09:36
	2014:12:37
	2015:03:38
	2015:06:39
	2015:09:40
	2015:12:41
	'

	if [ ! -f $SMDL ];then
		echo $LINE
		echo "${S}Setting distro level identification for internal script use now...${N}"

		case $month in
			01|02|03)
				month=03
				;;
			04|05|06)
				month=06
				;;
			07|08|09)
				month=09
				;;
			10|11|12)
				month=12
				;;
		esac

		assembled="$year:$month"
		distroLevel=$( grep -Eo "$assembled:[0-9]{1,2}" <<< $distroLevels | cut -d ':' -f 3 )

		# set the distro level id number now
		echo $distroLevel > $SMDL
		DISTRO_LEVEL=$distroLevel
		log_function_data "DISTRO_LEVEL: $DISTRO_LEVEL"
	fi
	eval $LOGUE
}

# args: $1 - which source update
update_to_new_sources()
{
	eval $LOGUS
	local grepSearch=''
	local searchIdentifier=''
	local sourceFile=''
	local sourcesData=''
	local whichUpdate=''
	local doUpdate=''

	case $1 in
		aptosid)
			grepSearch='(aptosid.*[[:space:]](sid|unstable)|deb-sdx)'
			searchIdentifier='aptosid'
			sourceFile='aptosid.list'
			sourcesData='deb http://aptosid.com/debian/ sid main fix.main\n#deb-src http://aptosid.com/debian/ sid main fix.main'
			whichUpdate='aptosid'
			;;
		debian-sid)
			grepSearch='debian\.org.*[[:space:]](sid|unstable)'
			searchIdentifier='Debian Sid'
			sourceFile='debian.list'
			sourcesData='deb http://ftp.uk.debian.org/debian unstable main contrib non-free'
			whichUpdate='Debian Sid'
			;;
	esac
	create_apt_source_item "$grepSearch" "$sourceFile" "$sourcesData" "$searchIdentifier"
	# if we have to add in any sources to sources.list, we'll need to do a new update
	# we have to set the update flag to null here or the main updater
	# won't update the stuff
	if [ "$?" -eq 0 ];then
		doUpdate='true'
	else
		doUpdate='false'
	fi
	update_completion_handler "$doUpdate" $whichUpdate

	# we need to set the APTOSID_SOURCES global now to make sure it's correct
	set_distro_data 'force'
	eval $LOGUE
}

tweak_antix_vb_source()
{
	eval $LOGUS
	local fixVB=$( grep -E '^deb[[:space:]].*virtualbox.*' $EAS )

	if [ -n "$fixVB" ];then
		echo "${S}Commenting out broken virtualbox repo ...${N}"
		sed -i -r 's%^(deb[[:space:]].*virtualbox.*)%##\1%g' $EAS
	fi
	eval $LOGUE
}

tweak_antix_sources()
{
	eval $LOGUS
	local fixDM=$( grep -E '^#.*deb[[:space:]].*ian-mult.*unstable.*' $EAS )
	local fixDS=$( grep -E '^#.*deb[[:space:]].*debian\.org.*unstable.*' $EAS )
	local doUpdate=''

	if [ -n "$fixDM" ];then
		echo "${S}Removing uncommented unstable source...${N}"
		sed -i -r 's%^#.*(deb[[:space:]].*ian-mult.*unstable.*)%\1%g' $EAS
		doUpdate='true'
	fi
	if [ -n "$fixDS" ];then
		echo "${S}Removing uncommented Debian unstable source...${N}"
		sed -i -r 's%^#.*(deb[[:space:]].*debian\.org.*unstable.*)%\1%g' $EAS
		doUpdate='true'
	fi
	# tweak_antix_vb_source

	update_completion_handler "$doUpdate" 'anti-X unstable'
	eval $LOGUE
}

# args: $1 - doUpdate; $2 - which update
update_completion_handler()
{
	eval $LOGUS
	local doUpdate=$1 whichUpdate=$2

	if [ "$doUpdate" == 'true' ];then
		UPDATED=''
		apt_update_handler 'distro-conversion'
	else
		echo "$SPACER${M}You already appear to have ${C}$whichUpdate${M} sources installed, continuing...${N}"
		log_function_data "Sources already installed: $whichUpdate"
	fi
	eval $LOGUE
}

antix_fix_1()
{
# 	eval $LOGPS
# 	run_script_import $LIB_2008_FIXES
# 	libavutil_fix_1
# 	eval $LOGPE
	:
}

###**EOF**###


syntax highlighted by Code2HTML, v. 0.9.1