#!/bin/bash
# ==============================================================================
# title			:TheeMahn's O/S Builder
# description	:Builds Ultimate Edition Operating Systems.
# author		:theemahn <theemahn@ultimateedition.info>
# date			:05/26/2016
# version		:1.9.7
# usage			:tmgrub --help
# manual		:man tmosb
# notes			:See change-log below for further information.
# ==============================================================================
# Change-log:
#	1.8.8:	Initial public release
#
#	1.8.9:	Internal test release.
#
#	1.9.0:	Public release, added aditional DE (Desktop Environments)
#			Added support for foreign Architectures PPC and ARM
#			Multitude of bug fixes
#
#	1.9.1	Bug fixes, added ability to set the default desktop
#			environment (DE).
#
#	1.9.2	Bug squashing release, introduced internal --BUILDALL -YES
# 			Will build all x86 and x64 based Operating systems back to back.
#
#			Initated the anti-malware initive, there will be no
#			spyware and will write code to not only remove malicous
#			software, but increase end user privacy.
#	1.9.3	Introduction of Vivid Vervet (Ubuntu 15.04)
#
#			Repaired modemmanager issues
#
#	1.9.4	Added distribution upgrade fixes everything in round #1
#
#	1.9.5	Version bump
#
#	1.9.6	Added End dist-upgrade to grab all updates in one sweep.
#
#	1.9.7	Closed the LTS (Long Term Supported) Gap.
#	2.0.3   Added service detection / implementation.
#				Fixed properly addressing version for grub menu.
#	2.0.7	Added initial support for "Jammy Jellyfish" / Ultimate Edition 7.4 & 7.5
# ==============================================================================
# Version Control
APPNAME="TheeMahn O/S Builder"
PROGNAME="tmgrub"
BUILDDATE="12/02/2021"
VERSION="2.0.7"
WEBSITE="os-builder.com"
AUTHOR="TheeMahn"
EMAIL="<$AUTHOR@${WEBSITE}>"
source ultimate-common
ROOTFOLDER="http://os-builder.com/UETOYS"
THEMEFOLDER="http://os-builder.com/themes"

declare -a ANTIMALWARE=('libzeitgeist-2.0-0-999.deb' 'libzeitgeist-999.deb' 'zeitgeist-999.deb' 'zeitgeist-core-999.deb' 'zeitgeist-datahub-999.deb');
DISTREL=$(cat /etc/lsb-release | sed -n 's/^DISTRIB_RELEASE=[ \t]*\(.*\)/\1/p' 2>/dev/null)

SETDEFAULT=$(echo "$*" | grep -i "defaultde=")
if [[ "${SETDEFAULT}" ]]; then
	DEFAULTDE=$(echo "$*" | grep -i 'defaultde=' | sed 's/^.*defaultde=//g' | cut -d' ' -f1)
	DEFAULTDE=$(echo "${DEFAULTDE}" | tr '[:lower:]' '[:upper:]')
fi
DEBUG=$(echo "$*" | grep -i "debug")
if [[ "${DEBUG}" ]]; then
	echo "DEBUGGING: 1:${1} 2:$2 3:$3 4:$4 5:$5 6:$6 7:$7 *:$*"
fi
MSERVER=$(grep -i "minimal" /etc/lsb-release)
# EXTRA USAGE, custom written...
# update-alternatives --list desktop-background | xargs -n 1 update-alternatives --remove desktop-background

Timer "Start" "${APPNAME}"

FinalCheck () {
	declare -a LASTCHECK=();
	LASTCHECK=$(mount | grep "none" | sort -r | grep "${PWD}" | cut -d " " -f3)
	if [[ "${LASTCHECK[@]}" ]]; then
		Encapsulate "We have hooks in ${PWD} as: ${LASTCHECK}"
		Encapsulate "We are going to forefully unhook them & re-sync."
		for EACH in "${LASTCHECK[@]}"
		do
			Encapsulate "UNMOUNING: ${EACH}"
		done
		#echo "Bailing..."
		#exit 1;
		mount | grep "none" | sort -r | grep "${PWD}" | cut -d " " -f3 | umount -f
		sync
	else
		Encapsulate "No hooks in the O/S."
	fi
}

# Check inode of rootfs if anything other then 2 we are in a chroot environment
# use above IUSER results to further our cause.& guarantee our success ;)
# Inform user of current findings:

# Turn off end user prompting
export DEBIAN_FRONTEND=noninteractive

ValidateURL() {
	EXISTS=$(wget -S --spider "${1}"  2>&1 | grep 'HTTP/1.1 200 OK')
	if [[ "${EXISTS}" ]]; then
		Encapsulate "Package: ${1} exists."
		return 0
	else
		Error "Package: ${1} does not exist. Your custom grub will be minimally customized."
		return 1
	fi
}

FireFox () {
	declare -a FFPREFS=( '7qdy7sjf.default' 'q2l51o82.default' )
    if [[ -f "/etc/lsb-release" ]]; then
        CODENAME=$(grep -i "codename" /etc/lsb-release | cut -d "=" -f2)
		ISLTS=$(grep -i "LTS" /etc/lsb-release)
		Center "Distro release info:"
		FullBar
		lsb_release -a
		FullBar
		DEVELOPER=$(grep -i "developer" /etc/lsb-release)
        if [[ "${DEVELOPER}" ]]; then
            DISTTYPE="Developer"
        fi
   		LITE=$(grep -i "lite" /etc/lsb-release)
        if [[ "${LITE}" ]]; then
            DISTTYPE="Lite"
        fi
   		GAMERS=$(grep -i "gamers" /etc/lsb-release)
   		if [[ "${GAMERS}" ]]; then
            DISTTYPE="Gamers"
        fi
   		SERVER=$(grep -i "server" /etc/lsb-release)
   		if [[ "${SERVER}" ]]; then
            DISTTYPE="Server"
			MOTD=$(sudo run-parts /etc/update-motd.d/)
        fi
		MSERVER=$(grep -i "minimal" /etc/lsb-release)
		if [[ "${MSERVER}" ]]; then
            DISTTYPE="Minimal Server"
			MOTD=$(sudo run-parts /etc/update-motd.d/)
        fi
    else
        CODENAME="Unknown" # This is not an exit event
    fi
    CODENAME="${CODENAME^}"
	FFINSTALLED=$(type -p firefox)
    if [[ "${FFINSTALLED}" ]]; then
	    FIREFOXVERSION=$(firefox --version | grep 'Mozilla Firefox' | sed "s/Mozilla Firefox //g" 2>/dev/null)
		for EACH in "${FFPREFS[@]}"
		do
	    	if [[ -d "/etc/skel/.mozilla/firefox/${EACH}" ]]; then
			FPREFS="/etc/skel/.mozilla/firefox/${EACH}/prefs.js"
	    	DATE=$(date +%Y%m%d%H%M)
	    		if [[ "${FIREFOXVERSION}" && -f "${FPREFS}" ]]; then
		    		Encapsulate "Setting firefox version ${FIREFOXVERSION} User Agent to:"
                    if [[ "${ISLTS}" ]]; then
                        if [[ "${DISTTYPE}" ]]; then
		    		        Encapsulate "Mozilla/5.0 (X11; Ultimate Edition ${DISTREL} ${DISTTYPE} LTS; Linux x86_64; rv:${FIREFOXVERSION}) Gecko/20100101 Firefox/${FIREFOXVERSION}"
        		    		sed -i "s/#CODENAME/${CODENAME}/g" "${FPREFS}"
    	    	    		sed -i "s/#FIREFOXVERSION/${FIREFOXVERSION}/g" "${FPREFS}"
                            sed -i "s/#DISTTYPE/${DISTTYPE}/g" "${FPREFS}"
    	    	    		sed -i "s/#DIST/${DISTREL}\ LTS/g" "${FPREFS}"
    	    	    		FullBar
    	    	        else
    	    	            Encapsulate "Mozilla/5.0 (X11; Ultimate Edition ${DISTREL} LTS; Linux x86_64; rv:${FIREFOXVERSION}) Gecko/20100101 Firefox/${FIREFOXVERSION}"
        		    		sed -i "s/#CODENAME/${CODENAME}/g" "${FPREFS}"
    	    	    		sed -i "s/#FIREFOXVERSION/${FIREFOXVERSION}/g" "${FPREFS}"
							sed -i "s/#DISTTYPE/${DISTTYPE}/g" "${FPREFS}"
    	    	    		sed -i "s/#DIST/${DISTREL}\ LTS/g" "${FPREFS}"
    	    	    		FullBar
    	    	        fi
	    	        else
	    	            Encapsulate "Mozilla/5.0 (X11; Ultimate Edition ${DISTREL}; Linux x86_64; rv:${FIREFOXVERSION}) Gecko/20100101 Firefox/${FIREFOXVERSION}"
    		    		sed -i "s/#CODENAME/${CODENAME}/g" "${FPREFS}"
	    	    		sed -i "s/#FIREFOXVERSION/${FIREFOXVERSION}/g" "${FPREFS}"
						sed -i "s/#DISTTYPE/${DISTTYPE}/g" "${FPREFS}"
	    	    		sed -i "s/#DIST/${DISTREL}/g" "${FPREFS}"
	    	        fi
	    		fi
			fi
		done
    fi
}

#Smash spyware, we want our users free to do as they like w/o being spied on...
AntiMalware () {
	Center "Pre-injecting Anti-malware software."
	for EACHPACKAGE in "${ANTIMALWARE[@]}"
	do
		TESTPACKAGE=$(dpkg -l | grep "${EACHPACKAGE}") 2>/dev/null
		if [[ "${TESTPACKAGE}" ]];then
			Encapsulate "${EACHPACKAGE} dumby package already installed."
		else
			URL="http://os-builder.com/UETOYS/${EACHPACKAGE}"
			Download "$URL"
			if [[ -f "${EACHPACKAGE}" ]];then
				Encapsulate "Installing ${EACHPACKAGE} dumby package."
				INSTALL=$(dpkg -i "${EACHPACKAGE}" 2>/dev/null)
                if [[ "${INSTALL}" ]]; then
                    Encapsulate "${EACHPACKAGE} installation successful."
                fi
				mkdir -p "/lib/modules/" # A FIX: LAST VESTAGE OF DEVS MIS-UNDERSTANDING HEY THAT FOLDER JUST MAY NOT BE THERE...
			fi
		fi
	done
	# Begin cycling array - allows for future introduction of other nasty programs
	#for EACH in "${MALWARE[@]}"
	#do
		# Check for installation of spyware one program at a time.
	#	INSTALLED=$((dpkg-query -l ${EACH} | grep 'ii')2>/dev/null)
	#	if [[ ${INSTALLED} ]]; then
	#		# Thusly inform the user there is spyware in thier system.
	#		Center "MALWARE detected: ${EACH} purging ${EACH} from the system."
	#		# Scrap it from thier system.
	#		apt-get remove --purge -y -f ${EACH}
	#	fi
	#done
}

# Dump program header
VersionDump

finish () {
  #apt-get autoclean
	echo "Normally cache would be cleaned here."
}

trap finish EXIT

KernelSanders () {
	# We are going to build a database of Linux kernels on a large scale.  Tripple nested array.
	declare -a KERNELTYPES=( "generic" "lowlatency" );  # Start simple
	for EACH in "${KERNELTYPES[@]}"
	do
		GREPIT=$(echo "$*,," | grep "${EACH}")
		if [[ "${GREPIT}" ]]; then
			SELECTEDTYPE="${EACH}"
		fi
	done
	if [[ "${SELECTEDTYPE}" ]]; then
		Encapsulate "User has requested: ${SELECTEDTYPE}"
	else
		Encapsulate "No kernel specified, defaulting to: ${SELECTEDTYPE}"
		SELECTEDTYPE="generic"
	fi
	declare -a LATESTKERNEL=(); # Create an array to store the latest of each type.
	declare -a REPOSITORIES=(); # Let's not piss around, multiple sources.
	declare -a INSTALLCOMMAND=(); # Command that will be used to install the Kernel & dependancies.
	declare -a INSTALLSHELL=(); # Selected kernel
	INDEX=0 # Reset the index
	for EACH in "${KERNELTYPES[@]}"
	do
		(( INDEX = INDEX +1 ))
		LATESTKERNEL[${INDEX}]=$(apt-get install linux-image-*-"${EACH}" 2> /dev/null | tail -1 | cut -d ":" -f3 | cut -d " " -f2 | sed "s/linux-image//g")
		INSTALLCOMMAND[${INDEX}]="apt-get install -f -y --allow-unauthenticated linux-{image,headers,modules}${LATESTKERNEL[${INDEX}]}"
		INSTALLSHELL[${INDEX}]="${LATESTKERNEL[${INDEX}]}"
	done
	if [[ "${INDEX}" -gt 1 ]]; then
		INDEX=0 # Reset the Index.
		Encapsulate "Information found:"
		for EACH in "${LATESTKERNEL[@]}"
		do
			(( INDEX = INDEX +1 ))
			Encapsulate "linux-image${EACH} found installation command: ${INSTALLCOMMAND[${INDEX}]}"
			if [[ "${SELECTEDTYPE}" ]]; then
				GREPIT=$(echo "${EACH}" | grep -i "${SELECTEDTYPE}")
			fi
			if [[ "${GREPIT}" ]]; then
				Encapsulate "Installing: ${INSTALLCOMMAND[${INDEX}]}, please wait..."
				INSTALLIT=$(apt-get install -f -y --allow-unauthenticated linux-{image,headers,modules}${LATESTKERNEL[${INDEX}]} dkms bcmwl-kernel-source)
			fi
		done
	else
		Error "No Kernel found."
	fi
}

ValidateURL() {
	EXISTS=$(wget -S --spider "${1}"  2>&1 | grep 'HTTP/1.1 200 OK')
	if [[ "${EXISTS}" ]]; then
		Encapsulate "Package: ${1} exists."
		return 1
	else
		Error "Package: ${1} does not exist. Your custom grub will be minimally customized."
		return 0
	fi
}

BlueToothBug() {
    INSTALLED=$((dpkg-query -l "blueman" | grep "iF")2>/dev/null)
    FTO="/var/lib/dpkg/info/blueman.postinst"
    if [[ "${INSTALLED}" ]]; then
        Encapsulate "Blueman (Bluetooth app) is broken rectifying: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=878814"
        if [[ -f "${FTO}" ]]; then
            sed -i "s/set/#set/g" "${FTO}"
            apt-get install -f -y
            INSTALLED=$((dpkg-query -l "blueman" | grep "ii")2>/dev/null)
            if [[ "${INSTALLED}" ]]; then
                Encapsulate "Blueman (Bluetooth app) is fixed. You are welcome ;)"
            else
                Error "Fix failed.  You will have no Bluetooth services in this O/S."
            fi
        fi
    fi
}

UpdateGrub () {
	GRUBB=$(type -p update-grub)
	if [[ -f "/etc/modprobe.d/blacklist_uas.conf" ]]; then
		TESTADD=$( grep -i "quirk" /etc/modprobe.d/blacklist_uas.conf )
		if [[ "${TESTADD}" ]]; then
			Encapsulate "Quirk bug for USB 3.1 bug has already been applied."
		else
			Encapsulate "Applying Quirk bugfix for USB 3.1."
			echo options usb-storage quirks=174c:55aa:u | tee /etc/modprobe.d/blacklist_uas.conf
		fi
	else
		touch "/etc/modprobe.d/blacklist_uas.conf"
		Encapsulate "Applying Quirk bugfix for USB 3.1."
		echo options usb-storage quirks=174c:55aa:u | tee /etc/modprobe.d/blacklist_uas.conf
	fi
	if [[ "${GRUBB}" ]]; then
		Encapsulate "Updating Grub..."
		sudo update-grub 2>/dev/null & Spinner "Updating Grub..."
		Encapsulate "Updating initramfs..."
		sudo update-initramfs -u -k all >/dev/null 2>&1 & Spinner "Updating Initramfs..."
		if [[ "$?" != 0 ]]; then
			Error "Initramfs failed to update."
			Encapsulate "Exiting..."
			exit 1
		else
			Encapsulate "Initramfs updated successfully."
		fi
		FullBar
	fi
}

CustomGrub () {
	INSTALLED=$(type -p grub2)
	if ! [[ "${INSTALLED}" ]]; then
		Encapsulate "Attempting to rectify missing grub."
		apt-get install --yes --assume-yes grub2
	fi
    QUOTE='"'
	if ! [[ "${ARCH}" == "armhf" ]]; then
		INSTALLED=$((dpkg-query -l "${GRUBPACKAGES}" | grep 'ii')2>/dev/null)
		if [[ -f "/etc/default/grub" || "${INSTALLED}" ]]; then
			PRECUSTOM=$(grep -i "${DISTREL}" /etc/default/grub 2>/dev/null)
			if ! [[ "${PRECUSTOM}" ]]; then
				GFONT=$(type -p grub-mkfont)
				if [[ -f "/usr/share/fonts/truetype/liberation/LiberationMono-Bold.ttf" ]]; then
					if [[ "${GFONT}" ]]; then
						Encapsulate "Customizing the Grub Menu, please wait."
						#Build font
						Encapsulate "Building grub font..."
						grub-mkfont --size=16 --output=/boot/grub/liberation.pf2 /usr/share/fonts/truetype/liberation/LiberationMono-Bold.ttf 2>/dev/null
						if ! [[ -f "/etc/default/grub" ]]; then
							echo "GRUB_BACKGROUND=${QUOTE}/usr/share/wallpapers/Ultimate_Edition_${DISTREL}.png${QUOTE}
export GRUB_MENU_PICTURE=${QUOTE}/usr/share/wallpapers/Ultimate_Edition_${DISTREL}.png${QUOTE}
export GRUB_COLOR_NORMAL=${QUOTE}black/black${QUOTE}
export GRUB_COLOR_HIGHLIGHT=${QUOTE}red/black${QUOTE}
GRUB_FONT=${QUOTE}/boot/grub/liberation.pf2" > "/etc/default/grub"
						else
							PROPER=$(grep -i "GRUB_BACKGROUND=" "/etc/default/grub")
							if ! [[ "${PROPER}" ]]; then
								echo "GRUB_BACKGROUND=${QUOTE}/usr/share/wallpapers/Ultimate_Edition_${DISTREL}.png${QUOTE}
export GRUB_MENU_PICTURE=${QUOTE}/usr/share/wallpapers/Ultimate_Edition_${DISTREL}.png${QUOTE}
export GRUB_COLOR_NORMAL=${QUOTE}black/black${QUOTE}
export GRUB_COLOR_HIGHLIGHT=${QUOTE}red/black${QUOTE}
GRUB_FONT=${QUOTE}/boot/grub/liberation.pf2" >> "/etc/default/grub"
							fi
						fi
					else
						Error "ERROR: grub-mkfont not availiable, grub will not be customized."
					fi
				else
					Error "Liberation font is not installed possibly a fatal error for grub customization."
				fi
			else
				Encapsulate "Grub menu is already customised."
			fi
		else
			Error "Grub is currently not installed."
		fi
	else
		Encapsulate "No Grub customization for arm based products are currently supported."
	fi
	# ultimate-edition-6.3-grub_all.deb
	GENPACKAGE="${THEMEFOLDER}/ultimate-edition-grub-${DISTREL}"
	GENPACKAGE+="_all.deb"
	DL="ultimate-edition-grub-${DISTREL}"
	DL+="_all.deb"
	VALID=$(ValidateURL "${GENPACKAGE}")
	Download "${GENPACKAGE}"
	if [[ -f "${DL}" ]]; then
		dpkg -i "${DL}"
	fi
	INSTALLED=$((dpkg-query -l "bcmwl-kernel-source" | grep "ii")2>/dev/null)
	if ! [[ "${INSTALLED}" ]]; then
		Encapsulate "Installing additional WIFI support, please wait..."
		#apt-get install -f -y bcmwl-kernel-source 2>/dev/null
		Encapsulate "Verifying full network capabilities are incorporated in the O/S"
		INSTALLED=$((dpkg-query -l "network-manager" | grep "ii")2>/dev/null)
		CHECK=$((dpkg-query -l "network-manager-gnome" | grep "ii")2>/dev/null)
		if [[ "${CHECK}" && "${INSTALLED}" ]]; then
			Encapsulate "Network support installed, configured and supported: Yes"
		else
			if ! [[ "${MSERVER}" ]]; then
				Encapsulate "Full Network Support is not installed, configured and supported... Rectifying, please wait."
				# Fix for broken package in network-manager
				#mkdir -p /etc/init.d/
				#touch /etc/init.d/modemmanager
				apt-get install -f -y network-manager 2>/dev/null
			else
				Encapsulate "Full Network Support is not installed, minimal server detected... Rectifying, please wait."
				apt-get install -f -y network-manager 2>/dev/null
			fi
		fi
		Encapsulate "WIFI support already installed."
		Encapsulate "Updating grub & initramfs, please wait..."
		FullBar
	else
		INSTALLED=$((dpkg-query -l "network-manager" | grep "ii")2>/dev/null)
		CHECK=$((dpkg-query -l "network-manager-gnome" | grep "ii")2>/dev/null)
		if [[ "${CHECK}" && "${INSTALLED}" ]]; then
			Encapsulate "Network support installed, configured and supported: Yes"
		else
			if ! [[ "${MSERVER}" ]]; then
				Encapsulate "Full Network Support is not installed, configured and supported... Rectifying, please wait."
				# Fix for broken package in network-manager
				#mkdir -p /etc/init.d/
				#touch /etc/init.d/modemmanager
				#apt-get install -f -y network-manager network-manager-gnome 2>/dev/null
			else
				Encapsulate "Full Network Support is not installed, minimal server detected... Rectifying, please wait."
				apt-get install -f -y network-manager 2>/dev/null
			fi
		fi
	fi
}

ARCH=$(getconf LONG_BIT)
if [ "${ARCH}" == "64" ]; then
	ARCH="amd64"
else
	ARCH="i386"
fi

ARM=$(uname -a | grep -i "arm")
PPC=$(uname -a | grep -i "ppc")

if [[ "$PPC" ]]; then
	ARCH="powerpc"
	Center "powerpc based release detected."
fi

if [[ "$ARM" ]]; then
	Center "ARMHF based release detected."
	ARCH="armhf"
fi

root_inode=$(stat -c %i /);
if [ "$root_inode" -ne 2 ]; then
	Encapsulate "Chroot environment detected. Setting up appropriately."
else
	Encapsulate "Non-chroot environment detected. I refuse to execute. Exiting..."
	exit 1;
fi
if [[ -d "/tmp/" ]]; then
	cd "/tmp/" || exit 1;
fi
Encapsulate "Mounting necessary points."
mount -t devpts none /dev/pts >/dev/null 2>&1
mount -t proc none /proc >/dev/null 2>&1
mount -t sysfs none /sys >/dev/null 2>&1
export HOME=/root
export LC_ALL=C
Encapsulate "Updating sources, please wait."
apt-get update  >/dev/null 2>&1
Encapsulate "Forcing packages if any."

# FIX for mysqld
KILLALLINSTALLED=$(type -p killall)
if [[ "${KILLALLINSTALLED}" ]]; then
    KILLALL=$(killall mysqld >/dev/null 2>&1)
fi

apt-get install -f -y 2>/dev/null
Encapsulate "Distribution upgrading, please wait..."
apt-get dist-upgrade -f -y 2>/dev/null
apt-get install -f -y linux-firmware
KernelSanders "$@"
Encapsulate "Customising Grub..."
CustomGrub
Encapsulate "Detecting Kernel(s), there can be only one."
	if [[ -d "/boot/" ]]; then
		cd "/boot" || exit 1;
	else
		Error "DEBUG Critical Error: No /boot/ folder called from: ${PWD}"
		exit 1;
	fi
	shopt -s nullglob
	declare -a KERNELS=();
	declare -a KERNELCHECK=();
	KERNELS=(./initrd-*)
	declare -a REMOVEKERNEL=();
	TKERNELS="${#KERNELS[@]}"
	if [[ "${TKERNELS}" -gt 1 ]]; then
		Encapsulate "Multiple Kernels detected: ${TKERNELS}"
		#ls -la /boot/
		#exit 1;
		#SCRAP=$(dpkg -l 'linux-*' | sed  '/^ii/!d;/'"$(uname -r | sed "s/\(.*\)-\([^0-9]\+\)/\1/")"'/d;s/^[^ ]*  [^ ]* \([^ ]*\).*/\1/;/[0-9]/!d' | xargs sudo apt-get -y purge)
		INDEX=0
		for EACH in "${KERNELS[@]}"
		do
            TESTKERNEL=$( echo "${KERNELS[0]}"| sed "s/.\/initrd.img-//g" | sed "s/-generic//g" )
			CURRENT=$(echo "${EACH}" | sed "s/.\/initrd.img-//g" | sed "s/-generic//g" )
            #if [[ "$TESTKERNEL" -gt "$CURRENT" ]]; then
            #    echo "$TESTKERNEL is greater than $CURRENT"
            #    echo "Processing $CURRENT via Grep"
            #else
            #    echo "$CURRENT is greater than $TESTKERNEL"
            #fi
	   		if [[ "$INDEX" == "${TKERNELS}" ]]; then
				Encapsulate "Keeping Kernel: ${EACH}"
			else
				Encapsulate "Removing old Kernel ${EACH}"
				KERNEL=$(echo "${EACH}" | cut -d '-' -f2,3)
				Encapsulate "Purging old Kernel: ${KERNEL}"
				dpkg -l | grep "${KERNEL}" | awk '{print $2}' | xargs apt-get remove --purge -f -y
				IMAGE="linux-image-${KERNEL}"
				HEADERS="${KERNELNAME}-generic"
				EXTRA="linux-image-extra-${KERNEL}"
				((INDEX +1))
				# Verify installation of each? This sucks, I want 0 defects, extra code.  Welcome aboard a nested array.
				#TODO: add checks and balances.
				#for KERNELCHECK in ${KERNEL} ${KERNELNAME} $IMAGE $HEADERS $EXTRA
				#do
				#	INSTALLED=$(dpkg -l "${KERNEL}CHECK" | grep -i 'ii')
				#	if [[ "${INSTALLED}" ]];then
				#		Encapsulate "${KERNEL}CHECK is installed and will be removed, because we already have a predominant kernel."
				#		BUILDUNINSTALL+=" ${KERNEL}CHECK"
				#	fi
				#done
			fi
		done
	else
		Encapsulate "Congradulations only one kernel detected."
		UpdateGrub
		FullBar
	fi
cd "${INFOLDER}" || exit 1;
BlueToothBug
##CUSTOMIZE GRUB MENU
FullBar

INSTALLED=$(type -p grub2)
if ! [[ "${INSTALLED}" ]]; then
	Encapsulate "Attempting to rectify missing grub."
	apt-get install --yes --assume-yes grub2 linux-firmware
fi

if ! [[ "${ARCH}" == "armhf" ]]; then
	INSTALLED=$((dpkg-query -l "${GRUBPACKAGES}" | grep 'ii')2>/dev/null)
	if [[ -f "/etc/default/grub" || "${INSTALLED}" ]]; then
		PRECUSTOM=$(grep -i "${DISTREL}" /etc/default/grub 2>/dev/null)
		if ! [[ "${PRECUSTOM}" ]]; then
			GFONT=$(type -p grub-mkfont)
			if [[ "${GFONT}" ]]; then
				Encapsulate "Customizing the Grub Menu, please wait."
				#Build font
                if [[ -f "/usr/share/fonts/truetype/liberation/LiberationMono-Bold.ttf" ]]; then
    				Encapsulate "Building grub font..."
	    			grub-mkfont --size=16 --output=/boot/grub/liberation.pf2 /usr/share/fonts/truetype/liberation/LiberationMono-Bold.ttf 2>/dev/null
#{
#	    			echo "GRUB_BACKGROUND=${QUOTE}/usr/share/wallpapers/Ultimate_Edition_${DISTREL}.png${QUOTE}"
#	    			echo "export GRUB_MENU_PICTURE=${QUOTE}/usr/share/wallpapers/Ultimate_Edition_${DISTREL}.png${QUOTE}"
#	    			echo 'export GRUB_COLOR_NORMAL="black/black"'
#	    			echo 'export GRUB_COLOR_HIGHLIGHT="red/black"'
#	    			echo 'GRUB_FONT="/boot/grub/liberation.pf2"'
#} > "/etc/default/grub"
                else
                    Error "ERROR: Liberation ttf is not installed.  Grub font will not be customized."
                fi
			else
				Error "ERROR: grub-mkfont not availiable, grub will not be customized."
			fi
		else
			Encapsulate "Grub menu is already customised."
		fi
	else
		Error "Grub is currently not installed."
		exit 1;
	fi
else
	Encapsulate "No Grub customization for arm based products currently supported."
fi
if [[ "${DEBUG}" ]]; then
    echo "DEBUGGING GRUB:"
    cat "/etc/default/grub"
fi
INSTALLED=$((dpkg-query -l "bcmwl-kernel-source" | grep "ii")2>/dev/null)
if ! [[ "${INSTALLED}" ]]; then
	Encapsulate "Installing additional WIFI support, please wait..."
	#apt-get install -f -y bcmwl-kernel-source 2>/dev/null
	if ! [[ "${MSERVER}" ]]; then
		Encapsulate "Verifying full network capabilities are incorporated in the O/S"
		INSTALLED=$((dpkg-query -l "network-manager" | grep "ii")2>/dev/null)
		CHECK=$((dpkg-query -l "network-manager-gnome" | grep "ii")2>/dev/null)
	fi
	if [[ "${CHECK}" && "${INSTALLED}" ]]; then
		Encapsulate "Network support installed, configured and supported: Yes"
	else
		if ! [[ "${MSERVER}" ]]; then
			Encapsulate "Full Network Support is not installed, configured and supported... Rectifying, please wait."
			# Fix for broken package in network-manager
			mkdir -p /etc/init.d/
			touch /etc/init.d/modemmanager
			apt-get install -f -y network-manager 2>/dev/null #network-manager-gnome
		else
			Encapsulate "Minimal Server non-GUI version of network manager will now be installed."
			apt-get install -f -y network-manager 2>/dev/null
		fi
	fi
	Encapsulate "WIFI support already installed."
	Encapsulate "Updating grub & initramfs, please wait..."
	FullBar
else
	INSTALLED=$((dpkg-query -l "network-manager" | grep "ii")2>/dev/null)
	if ! [[ "${MSERVER}" ]]; then
		CHECK=$((dpkg-query -l "network-manager-gnome" | grep "ii")2>/dev/null)
		if [[ "${CHECK}" && "${INSTALLED}" ]]; then
			Encapsulate "Network support installed, configured and supported: Yes"
		else
			Encapsulate "No Network support installed, installing Network support... Please wait."
			mkdir -p /etc/init.d/
			touch /etc/init.d/modemmanager
			#apt-get install -f -y netplan 2>/dev/null # network-manager-gnome network-manager
			if [[ -f "/etc/default/netplan" ]]; then
				Encapsulate "Enabling Networking"
				echo "ENABLED=1" | tee /etc/default/netplan
				if ! [[ -d "/etc/systemd/network/" ]]; then
					mkdir -p "/etc/systemd/network/"
					if ! [[ -f "/etc/systemd/network/20-dhcp.network" ]]; then
						(echo [Match]; echo Name=en*; echo [Network]; echo DHCP=yes; echo DNS=8.8.8.8) > /etc/systemd/network/20-dhcp.network
					fi
				fi
			else
				Encapsulate "Creating configuration file for networking."
				echo "ENABLED=1" > "/etc/default/netplan"
				if ! [[ -d "/etc/systemd/network/" ]]; then
					mkdir -p "/etc/systemd/network/"
					if ! [[ -f "/etc/systemd/network/20-dhcp.network" ]]; then
						(echo [Match]; echo Name=en*; echo [Network]; echo DHCP=yes; echo DNS=8.8.8.8) > /etc/systemd/network/20-dhcp.network
					fi
				fi
			fi
		fi
	fi
fi
Encapsulate "Enabling Networking."
systemctl enable systemd-networkd
systemctl enable systemd-resolved
if [[ -f "/etc/systemd/user/default.target.wants/conky.service" ]]; then
	Encapsulate "Enabling Conky-Builder & Conky for all users."
	systemctl enable conky-builder --user
	systemctl enable conky --user
fi
if [[ -f "/etc/systemd/user/default.target.wants/nasup.service" ]]; then
	Encapsulate "Enabling Nasup service for users."
	systemctl enable nasup --user
fi
if [[ -f "/etc/systemd/system/default.target.wants/uno.service" ]]; then
	Encapsulate "Enabling UNO (Ultimate Networking Optimizer) for all users."
	systemctl enable uno
fi
if [[ -f "/etc/systemd/system/default.target.wants/nasup.service" ]]; then
	Encapsulate "Enabling Nasup System service for all users."
	systemctl enable nasup
fi

GRUBB=$(type -p update-grub)
if [[ "${GRUBB}" ]]; then
	UpdateGrub "$@"
fi
Encapsulate "Forcing additional packages if necessary."
dpkg --configure -a 2>/dev/null
apt-get install -f -y 2>/dev/null
GCONF=$(type -p update-gconf-defaults)
DCONF=$(type -p dconf)
SCHEMEAS=$(type -p glib-compile-schemas)
if [[ "${GCONF}" ]]; then
	Encapsulate "Updating gconf defaults."
	update-gconf-defaults 2>/dev/null
fi
if [[ "${DCONF}" ]]; then
	Encapsulate "Updating dconf."
	dconf update 2>/dev/null
fi
if [[ "${SCHEMEAS}" ]]; then
	Encapsulate "Updating Schemeas."
	glib-compile-schemas /usr/share/glib-2.0/schemas/ 2>/dev/null
fi
Center "Checking for broken services"
for BROKEN in "${BROKENSERVICES[@]}"
do
	Encapsulate "Checking for broken service: ${BROKEN}"
	INSTALLED=$((dpkg-query -l "${BROKEN}" | grep "ii")2>/dev/null)
	BROKENPACKAGE=$((dpkg-query -l "${BROKEN}" | grep "iF")2>/dev/null)
	if ! [[ "${INSTALLED}" ]]; then
		if [[ "${BROKENPACKAGE}" ]]; then
			if ! [[ -f "/etc/init.d/${BROKEN}" ]];then
				Error "Repairing ${BROKEN} issue."
				touch "/etc/init.d/${BROKEN}"
				apt-get install -f -y;
				#SUPPRESS=$(rm /etc/init.d/${BROKEN} 2>/dev/null)
			fi
		else
			Encapsulate "Package: ${BROKEN} is not installed, and not broken.  Not doing squat."
		fi
		#if [[ -f /etc/init.d/${BROKEN} ]]; then
		#	rm /etc/init.d/${BROKEN}
		#fi
	else
		Encapsulate "Service: ${BROKEN} is installed & not broken."
	fi
done

if [[ -f "/etc/init.d/ultimate-media" ]]; then
    Encapsulate "Activating services for boot ultimate-media:"
    SUPPRESS=$(update-rc.d ultimate-media defaults 2>/dev/null)
    SUPPRESS=$(update-rc.d ultimate-media enable 2>/dev/null)
    if [[ "${SUPPRESS}" ]]; then
        Encapsulate "Ultimate Media service successfully activated."
    fi
else
    Error "Ultimate Media is not installed, DLNA streaming service will be unavailible in this O/S."
fi

if [[ -e /etc/default/apport ]]; then
    Encapsulate "Disabling Apport."
    sed -i "s/enabled=1/enabled=0/" "/etc/default/apport"
    SYSCTL=$(type -p systemctl)
    if [[ "${SYSCTL}" ]]; then
        Encapsulate "Disabling Apport services."
        MODIFY=$(${SYSCTL} disable apport.service)
        MODIFY=$(${SYSCTL} disable apport-forward.socket)
    fi
fi

if [[ -e /usr/bin/whoopsie ]]; then
    if [[ "${SYSCTL}" ]]; then
        Encapsulate "Disabling woopsie."
        MODIFY=$(${SYSCTL} disable whoopsie.service)
        if [[ "${MODIFY}" ]]; then
            Encapsulate "Success."
        fi
    fi
fi
AntiMalware
FireFox
FinalCheck
FullBar
Encapsulate "Unmounting points..."
umount /dev/pts 2>/dev/null
umount /proc/sys/fs/binfmt_misc 2>/dev/null
umount /proc 2>/dev/null
umount /sys 2>/dev/null
Encapsulate "Cleaning up."
rm -rf /tmp/.* ~/.bash_history /home/root/.bash_history /root/.bash_history /etc/apt/*.save /etc/apt/sources.list.d/*.save /*.old 2>/dev/null
Encapsulate "Cleaning up configuration files & unecessary packages..."
FullBar
apt-get autoremove -y -f
dpkg --list | grep "^rc" | cut -d " " -f 3 | xargs dpkg --purge 2>/dev/null
rm DE 2>/dev/null
sync
INSTALLED=$((dpkg-query -l "python3" | grep 'ii')2>/dev/null)
if [[ "${INSTALLED}" ]]; then
    Encapsulate "Setting Python3 as the default interpreter."
    update-alternatives --install /usr/bin/python python /usr/bin/python3 10
fi
#declare -a NOUSER=();
#NOUSER=$(awk -F: '$3 == 999' /etc/passwd | cut -d ":" -f1)
#if [[ "${#NOUSER[@]}" -gt 0 ]]; then
#	for EACH in "${NOUSER[@]}"
#	do
#		Encapsulate "Changing ${EACH} user from 999 to 500 or the disk will not boot."
#		usermod -u 500 "${EACH}"
#	done
#else
#	Encapsulate "Congradulations, no apps installed tried to use 999 as a user."
#fi
Center "Exiting Chroot environment."
FullBar
exit

# apt-get install shim efibootmgr grub-efi-amd64-bin grub-efi-amd64-signed mokutil secureboot-db
# ==============================================================================
# This code was automatically cleaned up using code-cleanup
# title			:code-cleanup
# description		:Bash code cleanup script
# Author		:root
# date			:10/23/2013
# version		:1.7.2-1
# http://ultimateedition.info/
# ==============================================================================
