#!/bin/bash
# ==============================================================================
# title			:ultimate-edition-core-builder
# description	:Builds Ultimate Edition core files.
# author		:theemahn <theemahn@ultimateedition.info>
# date			:06/04/2016
# version		:1.9.7
# usage			:uecorebuilder --help
# manual		:man uecorebuilder
# 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
#			with 0 user intervention. Introduction of software automation.
#
#			Initated the anti-malware initive, there will be no spyware in
#			Ultimate Edition. Code written to not only remove malicous
#			software, but increase end user privacy.
#
#			Removed case sensitivity in command line interpreter:
#			tmosb --build ultimate-edition-4.4-x64.iso KdE MaTe LXQT awesome
#			will now work. Command line interpreter now rejects all non-
#			applicable information.
#
#			Fixed bugs in directory detection of current build, souped up eyecandy
#			Updated donors software to automously generate list of donors, date they donated and amt.
#
#			Initiated the no-one left behind aspect train of thought.
#			Ultimate Edition enters the server world.
#			General server configation begins - Apache, Mysql, Wordpress
#			all command line switchabilty in the build process.
#
#			A few extra hundred O/S's it will build.
#
#		1.9.3	Fixed hostname detection and set server setup website
#			at /var/www/$HOSTNAME for minimal server.
#
#		1.9.4	Added support for (Ubuntu Vivid 15.04)
#
#			Added initilal skelatal support for DE's (fully detected at build):
#			"MATE" "CINNAMON" "KDE" "GNOME" "LXQT"
#
#			Added bash auto-completion to uecorebuilder
#
#		1.9.5	Bumped
#
#		1.9.6	Added support for UE 5.0. & 5.1
#
#			Added support for technology culpits feel should w/o a doubt
#			the mainstay.
#
#			Shellchecked & repaired some errors (this app is huge, will take time)
#
#		1.9.7	Closed LTS (Long Term Supported) Gap.
#			Added "KeepCache" switch currently undocumented, case "inSenSitive" &
#			does not matter where you integrate it in the switch.
#
#			uecorebuilder - entirely re-built & shellchecked, 90% of errors gone.
#
#			Added support for 16.10 Yakkety Yak / Ultimate Edition 5.2 & 5.3
#		2.0.3	Added full server support (integrated server security)
#		2.0.7	Added initial support for "Jammy Jellyfish" / Ultimate Edition 7.4 & 7.5
# ==============================================================================
# Version Control
APPNAME="TheeMahn O/S Builder"
PROGNAME="uecorebuilder"
VERSION="2.0.7"
BUILDDATE="12/02/2021"
WEBSITE="os-builder.com"
HOMEPAGE='http://ultimateedition.info/'
AUTHOR="TheeMahn"
EMAIL="<$AUTHOR@$WEBSITE>"

source /usr/share/ultimate_edition/ultimate-common

QUOTE='"'
DEBUG=$(echo "$*" | grep -i "debug")
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
# EXTRA USAGE, custom written...
# update-alternatives --list desktop-background | xargs -n 1 update-alternatives --remove desktop-background


# Distribution Layout VARS:
DIST_NAME="Ultimate_Edition"
DIST_VERSION="${2}"
DIST_NAME_LONG="Ultimate Edition ${2}"
_UNDERSCORED="Ultimate_Edition_${2}"
PACKAGE="ultimate-edition-core-files-0.0.1_all"
#PACKAGEVERSION='0.0.1'
PACKAGENAME="ultimate-edition-${2}-core-files"
PACKAGE="${PACKAGENAME}"
#BASEPACK="ultimate-edition"
declare -i INDEX;
declare -a FILETOPROCESS=();
declare -i array_counter;
OUTDISTRO="Ultimate Edition"

#declare -a THEMEING=('usr/share/glib-2.0/schemas/90_unity-greeter.gschema.override' 'etc/skel/.config/compiz-1/compizconfig/Default.ini' 'etc/skel/.gconf/apps/metacity/general/%gconf.xml');
INDEX=1

# Declare Integer for root user detection - Set as initial normal user.
declare -i TRUEROOT
TRUEROOT=1000
TRUEROOT=$(id -u)

Buildcore() {
	VersionDump
	BUILD=$(echo "$*" | grep -i "build")
	if [[ "$IUSER" != "root" && "$TRUEROOT" != "0" ]]; then
		Error "ERROR: This operation requires true root (su) access."
		FullBar
		exit 1;
	fi
	if [[ "${2}" == "" && "$BUILD" == "" ]]; then
		Error "Please provide switch.  Example:"
		Encapsulate "uecorebuilder --build 5.0 lite defaultde=xfce"
		FullBar
		exit 1;
	fi
	CVERSION="${2}"
	SETDEFAULT=$(echo "$*" | grep -i "defaultde=")
	COUNTDOTS=$(echo "${CVERSION}" |grep -o "\\." | wc -l)
	if [[ "${MSERVER}" ]]; then
		SERVER=""
		DTYPE="Minimal-Server"
		DE="NONE"
	fi
	if [[ "${COUNTDOTS}" -gt 1 ]]; then
		LONGVERSION="${CVERSION}"
		if [[ "${DEBUG}" ]]; then
			echo "DEBUG: DETECTED A LTS THAT IS GREATER THEN 2 DIGITS"
		fi
		LONGVERSION="${CVERSION%.*}"
		SHORTVERSION="${LONGVERSION}"
	else
		LONGVERSION="${CVERSION}"
		SHORTVERSION="${CVERSION}"
	fi
	BASEBUILD="${LONGVERSION}"
	LONGVERSION="${CVERSION}"
	if [[ "${DEBUG}" ]]; then
		echo "DEBUG: LONGVERSION SET AS: ${LONGVERSION}"
		echo "DEBUG: SHORTVERSION SET AS: ${SHORTVERSION}"
	fi
	for EACH in "${ISLTS[@]}"
	do
	    if [[ "${EACH}" == "${SHORTVERSION}" ]]; then
	        LTS="YES"
	    fi
	done
	if [[ "${MSERVER}" ]]; then
		SERVER=""
	fi

	EVENODD="${SHORTVERSION##*.}"
	if [[ "${DEBUG}" ]]; then
		echo "DEBUGGING: $EVENODD"
	fi
	#if [ $((EVENODD%2)) -eq 0 ]; then
	#	DTYPE="Standard"
	#	DE="gnome"
	#else
	#	DTYPE='Full'
	#	DE="kde"
	#fi
	if [[ "$GAMERS" ]]; then
		DTYPE="Gamers"
		if ! [[ "${DE}" ]]; then
			DE="mate"
		fi
	fi
	if [[ "${SERVER}" ]]; then
		DTYPE="Server"
		if ! [[ "${DE}" ]]; then
			DE="mate"
		fi
	fi
	if [[ "${MSERVER}" ]]; then
		SERVER=""
		DTYPE="Minimal-Server"
		DE="NONE"
	fi
	if [[ "$LITE" ]]; then
		DTYPE="Lite"
		if ! [[ "${DE}" ]]; then
			DE="mate"
		fi
	fi
	if [[ "${DEVELOPER}" ]]; then
		DTYPE="Developer"
		DEBTYPE="Developer"
	fi
	if ! [[ "${DEBTYPE}" ]]; then
		DEBTYPE="Standard"
	fi

	BASEBUILD="${SHORTVERSION}"

	array_counter=0
	#SPLIT=0
	for OST in "${UEARRAY[@]}"
	do
		if [[ "${DEBUG}" ]]; then
			echo "DEBUG: Comparing ${OST} to ${SHORTVERSION}"
		fi
		#SPLIT=$((array_counter / 2))
		if [[ "${OST}" == "${SHORTVERSION}" ]]; then
			if [[ "${DEBUG}" ]]; then
				echo "DEBUG: MATCH ${OST} AGAINST $BASEBUILD | ARRAYCOUNTER=$array_counter | DISTARRAY:${DISTARRAY[$array_counter]}"
			fi
			DIST="${OSARRAY[$array_counter]}"
			FULLNAME="${DISTARRAY[$array_counter]}"
			break;
		fi
		array_counter=$((array_counter+1))
	done
	if ! [[ "$FULLNAME" ]]; then
		array_counter=0
		BASEBUILD="${CVERSION}"
		for OST in "${UEARRAY[@]}"
		do
			if [[ "${OST}" == "$BASEBUILD" ]]; then
				if [[ "${DEBUG}" ]]; then
					echo "DEBUG: LTS DETECTED $BASEBUILD"
				fi
				DIST="${OSARRAY[$array_counter]}"
				FULLNAME="${DISTARRAY[$array_counter]}"
			fi

		done
	fi
	#Check for LTS
	array_counter=0
	LTS="NO"
	declare -i LENGTH;
	LENGTH="${#CVERSION}"
	#echo "LENGTH: ${LENGTH}"
	for OST in "${ISLTS[@]}"
	do
		if [[ "${CVERSION}" == "${OST}" || "${LENGTH}" -ge 4 ]]; then
			LTS="YES"
		fi
		array_counter=$((array_counter+1))
	done
	#if ! [[ "${DIST}" ]]; then
	#	DIST="${CVERSION}"
		#DIST=${2}
		#echo -e "${bldred}Critical ERROR: Halting..."
		#exit 0;
	#fi

	#LTS? 4.2.1 etc...
	#LONGLTS=$(echo "${2}" | grep -E '(.*\.){2}')
	#if [[ "${DTYPE}" ]]; then
	#	OUTDISTRO+=" ${DTYPE}"
	#fi
	if [[ "${MSERVER}" ]]; then
		DTYPE="minimal-server"
		SERVER=""
		DEFAULTDE="NONE"
		DE="NONE"
	fi
	DEBNAME=$(echo "${DTYPE}" | tr '[:upper:]' '[:lower:]')
	PACKAGENAME="ultimate-edition-${2}-${DEBNAME}-core-files"
	PACKAGE="${PACKAGENAME}"

	# check to see if a default desktop environment has been specified.
	SETDEFAULT=$(echo "$*" | grep -i "defaultde=")
	if [[ "${SETDEFAULT}" ]]; then
		DEBTYPE="standard"
		COMMANDISSUED=$(echo "$*" | tr '[:upper:]' '[:lower:]')
		DEFAULTDE=$(echo "${COMMANDISSUED}" | grep -i "defaultde=" | sed "s/^.*defaultde=//g" | cut -d" " -f1)
		if ! [[ "${DEFAULTDE}" ]]; then
			if [[ "${DE}" ]]; then
				Encapsulate "Default Desktop Environment (DE) based on ${CVERSION} as: ${DE}"
				DEFAULTDE="${DE}"
			fi
		else
				Encapsulate "Default Desktop Environment (DE) specified as: ${DEFAULTDE}"
				DE="${DEFAULTDE}"
		fi
	else
		if [[ "${DE}" ]]; then
			Encapsulate "Default Desktop Environment (DE) based on ${CVERSION} as: ${DE}"
			DEFAULTDE="${DE}"
		fi
		if ! [[ "${DEFAULTDE}" || "${MSERVER}" ]]; then
			Error "No default environment specified setting Mate as default."
			DEFAULTDE="mate"
		else
			DEFAULTDE="${DEFAULTDE}"
		fi
	fi

	if [[ "${MSERVER}" ]]; then
		DE="NONE"
		DTYPE="Minimal-Server"
		DEFAULTDE="NONE"
	fi

	# Requested additional DE(s)?

	OPTIONAL=""
	for EACH in "$@"
		do
		CHECKIT=$(echo "${EACH}" | tr '[:upper:]' '[:lower:]')
		for OPTIONAL in "${EXTRADE[@]}"
		do
			if [[ "${DEBUG}" ]]; then
				echo "DEBUG: Comparing: ${CHECKIT} to ${OPTIONAL}"
			fi
			if [[ "${CHECKIT}" == "${OPTIONAL}" ]]; then
				if [[ "${EXTRADES}" ]]; then
					EXTRADES+=", ${CHECKIT}"
				else
					EXTRADES="${CHECKIT}"
				fi
				((INDEX + 1))
			fi
		done
	done

	# Optional Architecture?
	ARCHITECTURES=$(echo "$*" | grep -i "${ARCHS}")
	for ARCHS in "${UEARCH[@]}"
	do
		if [[ "${ARCH}" == "${ARCHITECTURES}" ]]; then
			ARCH="${ARCHS}"
		fi
		if [[ "${DEBUG}" ]]; then
			echo "DEBUG: Comparing ${ARCHITECTURES} to ${ARCHS}"
			echo "DEBUG: Arch detected as: ${ARCHITECTURES}"
		fi
	done

	if ! [[ "${DTYPE}" ]]; then
		DTYPE="Full"
	fi

	if ! [[ "${ARCH}" ]]; then
		ARCH="All"
	fi

	if [[ "${EXTRADES}" ]]; then
		Encapsulate "Optional environment(s) detected: ${EXTRADES}"
	fi
	if [[ "${MSERVER}" ]]; then
		DE="NONE"
		DTYPE="Minimal-Server"
		DEFAULTDE="NONE"
	fi
	Encapsulate "Operating System Output: ${OUTDISTRO}"
	if [[ "${LONGVERSION}" ]]; then
		Encapsulate "Operating System base version requested: ${LONGVERSION}"
	else
		Encapsulate "Operating System base version requested: ${SHORTVERSION}"
	fi
	Encapsulate "Operating System distribution base: ${DIST}"
	Encapsulate "Distribution Long Name: $FULLNAME"
	Encapsulate "Distribution Type: ${DTYPE}"
	Encapsulate "Architecture: ${ARCH}"
	Encapsulate "Long Term Supported (LTS): ${LTS}"
	Encapsulate "Desktop Environment (DE): ${DEFAULTDE}"
	B="${DTYPE,,}"
	if ! [[ "${B}" ]] ; then
		if [[ "${LONGVERSION}" ]]; then
			REPLACEMENTVER="ultimate-edition-${LONGVERSION}-core-files"
		else
			REPLACEMENTVER="ultimate-edition-${SHORTVERSION}-core-files"
		fi
	else
		if [[ "${LONGVERSION}" ]]; then
			REPLACEMENTVER="ultimate-edition-${LONGVERSION}-${B}-core-files"
		else
			REPLACEMENTVER="ultimate-edition-${SHORTVERSION}-${B}-core-files"
		fi
	fi

	#DISTBASE="${DIST}"
	#UEVERSION="${1}"

	FullBar
	Center "Package to construct: ${REPLACEMENTVER}.deb"
	PACKAGENAME="${REPLACEMENTVER}"
	PACKAGE="${PACKAGENAME}"
	FullBar
	PROMPT=$(echo "$*" | grep -i "YES")
	if ! [[ "$PROMPT" ]]; then
			PromptYN "${txtwht}Is the above information correct (Y/N)? "
			case "${YN}" in
				[Nn]* ) echo -e "${txtrst}"; exit 0;;
				[Yy]* ) echo -e "${txtgrn}"
				Center "Initiating build of ${PACKAGENAME}.deb ...";;
				* ) echo "Please answer y or n.";;
			esac
	fi

	if [[ "$yn" == "n" ]]; then
		exit 0
	fi
	PACHAGENAME="${REPLACEMENTVER}"
	# DEBIAN STRUCTURE
	mkdir -p "${PACKAGE}/usr/share/doc/${PACKAGE}/"
	mkdir -p "${PACKAGE}/lib/plymouth/themes/"
	mkdir -p "${PACKAGE}/etc/lightdm/"
	mkdir -p "${PACKAGE}/etc/skel/.config/dconf/"
	mkdir -p "${PACKAGE}/etc/update-motd.d/"
	mkdir -p "${PACKAGE}/DEBIAN/"
	mkdir -p "${PACKAGE}/usr/share/glib-2.0/schemas/"
	mkdir -p "${PACKAGE}/usr/share/applications/"
	mkdir -p "${PACKAGE}/usr/share/python-apt/templates/"
	mkdir -p "${PACKAGE}/etc/dpkg/origins/"
	mkdir -p "${PACKAGE}/usr/lib/ubiquity/apt-setup/generators/"
	mkdir -p "${PACKAGE}/etc/xdg/autostart/"
	mkdir -p "${PACKAGE}/usr/share/applications/"
	mkdir -p "${PACKAGE}/usr/lib/"
	mkdir -p "${PACKAGE}/usr/share/python-apt/templates/"
	mkdir -p "${PACKAGE}/usr/share/ultimate_edition/"
	mkdir -p "${PACKAGE}/usr/share/lightdm/lightdm.conf.d/"
	mkdir -p "${PACKAGE}/etc/lightdm/lightdm.conf.d/"
	mkdir -p "${PACKAGE}/etc/lightdm/lightdm-gtk-greeter.conf.d/"

	#Turn off case sensitivity
	shopt -s nocasematch

	LIGHTDM="${PACKAGE}/usr/share/ultimate_edition/lightdm-ultimate.conf"
	DMRC="${PACKAGE}/etc/skel/.dmrc"
	# Check if we are creating a Lite distribution if so create auto login files for mate
	if [[ "${DTYPE}" == "Lite" || "${DEFAULTDE}" == "mate" ]]; then
		Encapsulate "Lite distribution or Mate set as default. Setting up auto login for mate."
		echo "[SeatDefaults]" > "${LIGHTDM}"
		echo "autologin-user=ultimate"  >> "${LIGHTDM}"
		echo "autologin-user-timeout=0" >> "${LIGHTDM}"
		echo "[SeatDefaults]" >> "${PACKAGE}/etc/lightdm/lightdm.conf.d/90-lightdm-ultimate.conf"
		echo "user-session=${DEFAULTDE}" >> "${PACKAGE}/etc/lightdm/lightdm.conf.d/90-lightdm-ultimate.conf"
		echo "greeter-session=unity-greeter" >> "${LIGHTDM}"
		echo "[SeatDefaults] " > "${PACKAGE}/usr/share/lightdm/lightdm.conf.d/90-ultimate.conf"
		echo "user-session=${DEFAULTDE}" >> "${PACKAGE}/usr/share/lightdm/lightdm.conf.d/90-ultimate.conf"
		echo "greeter-session=unity-greeter" >> "${PACKAGE}/usr/share/lightdm/lightdm.conf.d/90-ultimate.conf"
		echo "[Desktop]" > "${DMRC}"
		echo "Session=${DEFAULTDE}" >> "${DMRC}"
	fi

	# Gamers? Repeat above process, Gamers runs on a lite distribution to allow more space for games.
	if [[ "${DTYPE}" == "Gamers" || "${SERVER}" || "${DEFAULTDE}" == "mate" ]]; then
		Encapsulate "Lite distribution / server or Mate set as default. Setting up auto login for Mate."
		echo "[SeatDefaults]" > "${LIGHTDM}"
		echo "autologin-user=ultimate"  >> "${LIGHTDM}"
		echo "autologin-user-timeout=0" >> "${LIGHTDM}"
		echo "greeter-session=unity-greeter" >> "${LIGHTDM}"
		echo "[SeatDefaults]" >> "${PACKAGE}/etc/lightdm/lightdm.conf.d/90-lightdm-ultimate.conf"
		echo "user-session=${DEFAULTDE}" >> "${PACKAGE}/etc/lightdm/lightdm.conf.d/90-lightdm-ultimate.conf"
		echo "[Desktop]" > "${PACKAGE}/etc/skel/.dmrc"
		echo "Session=${DEFAULTDE}" >> "${PACKAGE}/etc/skel/.dmrc"
	fi
	if [[ "${DTYPE}" == "${MSERVER}" ]]; then
		Encapsulate "Minimal server distribution, no Desktop environment will be installed."
	fi

	# Enter bloatware KDE ;)
	if [[ "${DE}" == "KDE" || "${DEFAULTDE}" == "KDE" ]]; then
		Encapsulate "Odd number distribution detected. Setting up auto login for KDE."
{
		echo "[SeatDefaults]"
		echo "autologin-user=ultimate"
		echo "autologin-user-timeout=0"
        echo "greeter-session=unity-greeter"
} > "${LIGHTDM}"
{
		echo "[SeatDefaults]"
		echo "user-session=kde-plasma"
} > "${PACKAGE}/etc/lightdm/lightdm.conf.d/90-lightdm-ultimate.conf"
{
		echo "[Desktop]"
		echo "Session=kde-plasma"
} > "${PACKAGE}/etc/skel/.dmrc"
{
		echo "[SeatDefaults] "
		echo "user-session=kde-plasma"
		echo "greeter-session=unity-greeter"
} > "${PACKAGE}/usr/share/lightdm/lightdm.conf.d/70-kde-plasma.conf"
	fi
	if [[ "${DE}" == "TRINITY" || "${DEFAULTDE}" == "TRINITY" ]]; then
		Encapsulate "Odd number distribution detected. Setting up auto login for TRINITY."
{
		echo "[SeatDefaults]"
		echo "autologin-user=ultimate"
		echo "autologin-user-timeout=0"
        echo "greeter-session=unity-greeter"
} > "${LIGHTDM}"
{
		echo "[SeatDefaults]"
		echo "user-session=trinity"
} > "${PACKAGE}/etc/lightdm/lightdm.conf.d/90-lightdm-ultimate.conf"
{
		echo "[Desktop]"
		echo "Session=trinity"
} > "${PACKAGE}/etc/skel/.dmrc"
{
		echo "[SeatDefaults] "
		echo "user-session=trinity"
		echo "greeter-session=unity-greeter"
} > "${PACKAGE}/usr/share/lightdm/lightdm.conf.d/70-kde-trinity.conf"
	fi
	# Non odd release set gnome as default - Minimal server needs special attention, no DE
	if ! [[ "${MSERVER}" ]]; then
		if ! [[ -f "${LIGHTDM}" ]]; then
			if ! [[ "${DEFAULTDE}" ]]; then
				Encapsulate "Even release distribution detected. Setting up auto login for Gnome."
				echo "[SeatDefaults]" > "${LIGHTDM}"
				echo "autologin-user=ultimate"  >> "${LIGHTDM}"
				echo "autologin-user-timeout=0" >> "${LIGHTDM}"
				echo "[SeatDefaults]" >> "${PACKAGE}/etc/lightdm/lightdm.conf.d/90-lightdm-ultimate.conf"
				echo "user-session=${DEFAULTDE}" >> "${PACKAGE}/etc/lightdm/lightdm.conf.d/90-lightdm-ultimate.conf"
				echo "greeter-session=unity-greeter" >> "${LIGHTDM}"
				echo "[Desktop]" > "${PACKAGE}/etc/skel/.dmrc"
				echo "Session=${DEFAULTDE}" >> "${PACKAGE}/etc/skel/.dmrc"
				echo "[SeatDefaults] " > $"PACKAGE/usr/share/lightdm/lightdm.conf.d/70-kde-plasma.conf"
				echo "user-session=${DEFAULTDE}" >> "${PACKAGE}/usr/share/lightdm/lightdm.conf.d/70-kde-plasma.conf"
				echo "greeter-session=unity-greeter" >> "${PACKAGE}/usr/share/lightdm/lightdm.conf.d/70-kde-plasma.conf"
			fi
		fi
	else
		if ! [[ -f "${LIGHTDM}" ]]; then
			echo "[SeatDefaults]" > "${LIGHTDM}"
			echo "autologin-user=ultimate"  >> "${LIGHTDM}"
			echo "autologin-user-timeout=0" >> "${LIGHTDM}"
			echo "[SeatDefaults]" >> "${PACKAGE}/etc/lightdm/lightdm.conf.d/90-lightdm-ultimate.conf"
			echo "user-session=${DEFAULTDE}" >> "${PACKAGE}/etc/lightdm/lightdm.conf.d/90-lightdm-ultimate.conf"
			echo "greeter-session=unity-greeter" >> "${LIGHTDM}"
			echo "[Desktop]" > "${PACKAGE}/etc/skel/.dmrc"
			echo "Session=${DEFAULTDE}" >> "${PACKAGE}/etc/skel/.dmrc"
			echo "[SeatDefaults] " > "${PACKAGE}/usr/share/lightdm/lightdm.conf.d/70-kde-plasma.conf"
			echo "user-session=${DEFAULTDE}" >> "${PACKAGE}/usr/share/lightdm/lightdm.conf.d/70-kde-plasma.conf"
			echo "greeter-session=unity-greeter" >> "${PACKAGE}/usr/share/lightdm/lightdm.conf.d/70-kde-plasma.conf"
		fi
	fi

	# Default desktop environment specified?
	if [[ "${DEFAULTDE}" ]]; then
		DEFAULTDE=$(echo "${DEFAULTDE}" | tr '[:upper:]' '[:lower:]')
		Encapsulate "Setting ${DEFAULTDE} as default desktop environment (DE)."
		case "${DEFAULTDE}" in
			budgie)		if  [[ -f "${LIGHTDM}" ]]; then
						sed -i "s/user-session=.*/user-session=budgie-desktop/g" "${LIGHTDM}"
					else
						echo "[SeatDefaults]" > "${LIGHTDM}"
						echo "user-session=budgie-desktop" >> "${LIGHTDM}"
					fi
					if [[ -f "${DMRC}" ]]; then
						sed -i "s/Session=.*/Session=budgie-desktop/g" "${DMRC}"
					else
						echo "[Desktop]" > "${DMRC}"
						echo "Session=budgie-desktop" >> "${DMRC}"
					fi;;

			mate)		if  [[ -f "${LIGHTDM}" ]]; then
						sed -i "s/user-session=.*/user-session=mate/g" "${LIGHTDM}"
					else
						echo "[SeatDefaults]" > "${LIGHTDM}"
						echo "user-session=mate" >> "${LIGHTDM}"
					fi
					if [[ -f "${DMRC}" ]]; then
						sed -i "s/Session=.*/Session=mate/g" "${DMRC}"
					else
						echo "[Desktop]" > "${DMRC}"
						echo "Session=mate" >> "${DMRC}"
					fi;;

			LXqt)	if  [[ -f "${LIGHTDM}" ]]; then
						sed -i "s/user-session=.*/user-session=LX/g" "${LIGHTDM}"
					else
						echo "[SeatDefaults]" > "${LIGHTDM}"
						echo "user-session=LX" >> "${LIGHTDM}"
					fi
					if [[ -f "${DMRC}" ]]; then
						sed -i "s/Session=.*/Session=LX/g" "${DMRC}"
					else
						echo "[Desktop]" > "${DMRC}"
						echo "Session=LX" >> "${DMRC}"
					fi;;

			trinity)		if  [[ -f "${LIGHTDM}" ]]; then
						sed -i "s/user-session=.*/user-session=trinity/g" "${LIGHTDM}"
					else
						echo "[SeatDefaults]" > "${LIGHTDM}"
						echo "user-session=trinity" >> "${LIGHTDM}"
					fi
					if [[ -f "${DMRC}" ]]; then
						sed -i "s/Session=.*/Session=trinity/g" "${DMRC}"
					else
						echo "[Desktop]" > "${DMRC}"
						echo "Session=trinity" >> "${DMRC}"
					fi;;

			kde)		if  [[ -f "${LIGHTDM}" ]]; then
						sed -i "s/user-session=.*/user-session=kde-plasma/g" "${LIGHTDM}"
					else
						echo "[SeatDefaults]" > "${LIGHTDM}"
						echo "user-session=kde-plasma" >> "${LIGHTDM}"
					fi
					if [[ -f "${DMRC}" ]]; then
						sed -i "s/Session=.*/Session=kde-plasma/g" "${DMRC}"
					else
						echo "[Desktop]" > "${DMRC}"
						echo "Session=kde-plasma" >> "${DMRC}"
					fi;;

			xfce)		if  [[ -f "${LIGHTDM}" ]]; then
						sed -i "s/user-session=.*/user-session=xubuntu/g" "${LIGHTDM}"
					else
						echo "[SeatDefaults]" > "${LIGHTDM}"
						echo "user-session=xubuntu" >> "${LIGHTDM}"
					fi
					if [[ -f "${DMRC}" ]]; then
						sed -i "s/Session=.*/Session=xubuntu/g" "${DMRC}"
					else
						echo "[Desktop]" > "${DMRC}"
						echo "Session=xubuntu" >> "${DMRC}"
					fi;;

			lxde)		if  [[ -f "${LIGHTDM}" ]]; then
						sed -i "s/user-session=.*/user-session=Lubuntu/g" "${LIGHTDM}"
					else
						echo "[SeatDefaults]" > "${LIGHTDM}"
						echo "user-session=Lubuntu" >> "${LIGHTDM}"
					fi
					if [[ -f "${DMRC}" ]]; then
						sed -i "s/Session=.*/Session=Lubuntu/g" "${DMRC}"
					else
						echo "[Desktop]" > "${DMRC}"
						echo "Session=Lubuntu" >> "${DMRC}"
					fi;;

			awesome)	if  [[ -f "${LIGHTDM}" ]]; then
						sed -i "s/user-session=.*/user-session=awesome/g" "${LIGHTDM}"
					else

						echo "[SeatDefaults]" > "${LIGHTDM}"
						echo "user-session=awesome" >> "${LIGHTDM}"
					fi
					if [[ -f "${DMRC}" ]]; then
						sed -i "s/Session=.*/Session=awesome/g" "${DMRC}"
					else
						echo "[Desktop]" > "${DMRC}"
						echo "Session=awesome" >> "${DMRC}"
					fi;;

			gnome)		if  [[ -f "${LIGHTDM}" ]]; then
						sed -i "s/user-session=.*/user-session=gnome/g" "${LIGHTDM}"
					else
						echo "[SeatDefaults]" > "${LIGHTDM}"
						echo "user-session=gnome" >> "${LIGHTDM}"
					fi;;

			unity)		if  [[ -f "${LIGHTDM}" ]]; then
						sed -i "s/user-session=.*/user-session=unity/g" "${LIGHTDM}"
					else
						echo "[SeatDefaults]" > "${LIGHTDM}"
						echo "user-session=unity" >> "${LIGHTDM}"
					fi
					if [[ -f "${DMRC}" ]]; then
						sed -i "s/Session=.*/Session=unity/g" "${DMRC}"
					else
						echo "[Desktop]" > "${DMRC}"
						echo "Session=unity" >> "${DMRC}"
					fi;;

			fallback) 	if  [[ -f "${LIGHTDM}" ]]; then
						sed -i "s/user-session=.*/user-session=gnome-fallback/g" "${LIGHTDM}"
					else
						echo "[SeatDefaults]" > "${LIGHTDM}"
						echo "user-session=gnome-fallback" >> "${LIGHTDM}"
					fi
					if [[ -f "${DMRC}" ]]; then
						sed -i "s/Session=.*/Session=gnome-fallback/g" "${DMRC}"
					else
						echo "[Desktop]" > "${DMRC}"
						echo "Session=gnome-fallback" >> "${DMRC}"
					fi;;

			cinnamon) 	if  [[ -f "${LIGHTDM}" ]]; then
						sed -i "s/user-session=.*/user-session=cinnamon/g" "${LIGHTDM}"
					else
						echo "[SeatDefaults]" > "${LIGHTDM}"
						echo "user-session=cinnamon" >> "${LIGHTDM}"
					fi
					if [[ -f "${DMRC}" ]]; then
						sed -i "s/Session=.*/Session=cinnamon/g" "${DMRC}"
					else
						echo "[Desktop]" > "${DMRC}"
						echo "Session=cinnamon" >> "${DMRC}"
					fi;;

			touch)		if  [[ -f "${LIGHTDM}" ]]; then
						sed -i "s/user-session=.*/user-session=touch/g" "${LIGHTDM}"
					else
						echo "[SeatDefaults]" > "${LIGHTDM}"
						echo "user-session=touch" >> "${LIGHTDM}"
					fi
					if [[ -f "${DMRC}" ]]; then
						sed -i "s/Session=.*/Session=touch/g" "${DMRC}"
					else
						echo "[Desktop]" > "${DMRC}"
						echo "Session=touch" >> "${DMRC}"
					fi;;

			NONE)   	Encapsulate "Setting no default desktop environment (DE).";;
		esac
	fi
	if [[ "${MSERVER}" ]]; then
		DTYPE="minimal-server"
		SERVER=""
		DEFAULTDE="NONE"
		DE="NONE"
	fi
	# Begin Core files
	DTYPE=$(echo "${DTYPE}" | tr '[:upper:]' '[:lower:]')
	DTYPE="${DTYPE^}"
	if [[ "${DTYPE}" ]]; then
		DISTID="DISTRIB_ID=${QUOTE}"
		DISTID+="Ultimate Edition"
		DISTID+="${QUOTE}"
		echo "${DISTID}" > "${PACKAGE}/etc/lsb-release"
	else
		echo "DISTRIB_ID=${QUOTE}${DIST_NAME}${QUOTE}" > "${PACKAGE}/etc/lsb-release"
	fi
	if [[ "${LONGVERSION}" ]]; then
		OUTDISTRO+=" ${LONGVERSION}"
	else
		OUTDISTRO+=" ${CVERSION}"
	fi
	if [[ "${DTYPE}" ]]; then
		OUTDISTRO+=" ${DTYPE}"
	fi
	if [[ "${LTS}" == "YES" ]]; then
		OUTDISTRO+=" LTS"
	fi
	if [[ "${LONGVERSION}" ]]; then
		echo "DISTRIB_RELEASE=${LONGVERSION}" >> "${PACKAGE}/etc/lsb-release"
	else
		echo "DISTRIB_RELEASE=${SHORTVERSION}" >> "${PACKAGE}/etc/lsb-release"
	fi
	echo "DISTRIB_CODENAME=${DIST}" >> "${PACKAGE}/etc/lsb-release"
	echo "DISTRIB_DESCRIPTION=${QUOTE}${OUTDISTRO}${QUOTE}" >> "${PACKAGE}/etc/lsb-release"

	# Set issue
	echo ${OUTDISTRO}'\n \l' > "${PACKAGE}/etc/issue"
	echo "${OUTDISTRO}" > "${PACKAGE}/etc/issue.net"

	# Set os-release
	#NAME="Ubuntu"
	#VERSION="16.04 LTS (Xenial Xerus)"
	#ID=ubuntu
	#ID_LIKE=debian
	#PRETTY_NAME="Ubuntu 16.04 LTS"
	#VERSION_ID="16.04"
	#HOME_URL="http://www.ubuntu.com/"
	#SUPPORT_URL="http://help.ubuntu.com/"
	#BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"
	#UBUNTU_CODENAME=xenial

	if [[ "${DTYPE}" ]];then
		LONGNAME=$(echo "${DIST_NAME} ${DTYPE}" | sed "s/_/ /g")
		echo 'NAME="'"${DIST_NAME}"_"${DTYPE}"'"' > "${PACKAGE}/usr/lib/os-release"
	else
		LONGNAME="${DIST_NAME//_/ }"
		#LONGNAME=$(echo "${DIST_NAME}" | sed "s/_/ /g")
		echo 'NAME="'${DIST_NAME}'"' > "${PACKAGE}/usr/lib/os-release"
	fi
	HOMEURL='http://ultimateedition.info/'
	SUPPORT='http://forumubuntusoftware.info/'
	BUGREPORT='https://launchpad.net/ubuntu.ultimate/+filebug'
	DOCUMENTATION='https://forumubuntusoftware.info/viewforum.php?f=10'
	if [[ "${LONGVERSION}" ]]; then
		echo "VERSION=${LONGVERSION}" >> "${PACKAGE}/usr/lib/os-release"
	else
		echo "VERSION=${CVERSION}" >> "${PACKAGE}/usr/lib/os-release"
	fi
	echo 'ID="ultimate_edition"' >> "${PACKAGE}/usr/lib/os-release"
	echo "ID_LIKE=ubuntu" >> "${PACKAGE}/usr/lib/os-release"
	if [[ "${LONGVERSION}" ]]; then
		if [[ "${LTS}" == "YES" ]]; then
    		echo "PRETTY_NAME=${QUOTE}${LONGNAME} (${CVERSION}) LTS${QUOTE}" >> "${PACKAGE}/usr/lib/os-release"
        else
            echo "PRETTY_NAME=${QUOTE}${LONGNAME} (${CVERSION})${QUOTE}" >> "${PACKAGE}/usr/lib/os-release"
        fi
	else
	    if [[ "${LTS}" == "YES" ]]; then
    		echo "PRETTY_NAME=${QUOTE}${LONGNAME} (${CVERSION}) LTS${QUOTE}" >> "${PACKAGE}/usr/lib/os-release"
        else
            echo "PRETTY_NAME=${QUOTE}${LONGNAME} (${CVERSION})${QUOTE}" >> "${PACKAGE}/usr/lib/os-release"
        fi
	fi
	echo "VERSION_ID=${QUOTE}${CVERSION}${QUOTE}" >> "${PACKAGE}/usr/lib/os-release"
	echo "VERSION_CODENAME=${QUOTE}${DIST}${QUOTE}" >> "${PACKAGE}/usr/lib/os-release"
	echo "VARIANT=${QUOTE}${DTYPE}${QUOTE}" >> "${PACKAGE}/usr/lib/os-release"
	echo "HOME_URL=${QUOTE}${HOMEURL}${QUOTE}" >> "${PACKAGE}/usr/lib/os-release"
	echo "DOCUMENTATION_URL=${QUOTE}${DOCUMENTATION}${QUOTE}" >> "${PACKAGE}/usr/lib/os-release"
	echo "BUG_REPORT_URL=${QUOTE}${BUGREPORT}${QUOTE}" >> "${PACKAGE}/usr/lib/os-release"

	# Templates for synaptic etc.
	TEMPLATE=$(echo "${DIST_NAME}"_"${DTYPE}" | sed "s/_/ /g")
	TEMPLATE=$(echo "${TEMPLATE}" | sed -e "s/\b\(.\)/\u\1/g")
	TEMPLATE=$(echo "${TEMPLATE}" | sed "s/ /_/g")
	LOWERCASE=$(echo "${DIST_NAME}"_"${DTYPE}"  | tr '[:upper:]' '[:lower:]')
	TEMPLATE="Ultimate_Edition"
	# Data minipulation @ it's finest ;)
	cp "/usr/share/ultimate_edition/Ultimate_Edition.info" "${PACKAGE}/usr/share/python-apt/templates/${TEMPLATE}.info"
	cp "/usr/share/ultimate_edition/Ultimate_Edition.mirrors" "${PACKAGE}/usr/share/python-apt/templates/${TEMPLATE}.mirrors"
	#sed -i "s/Ubuntu/${TEMPLATE}/g" ${PACKAGE}/usr/share/python-apt/templates/${TEMPLATE}.info

	if [[ "${INJECTED}" ]]; then
		Encapsulate "Software center fix has been injected into the deb."
	else
		Encapsulate "Software center will not be installed on host system."
	fi

	# Create Message of the day
	if [[ -f "${PACKAGE}/etc/update-motd.d/10-help-text" ]]; then
		Encapsulate "Updating Message of the day."
		sed -i 's/URL=.*/URL=\"http:\/\/forumubuntusoftware.info\/"/g' "${PACKAGE}/etc/update-motd.d/10-help-text"
	fi

	#### CUSOMIZATION SECTION ####  Unused currently.
	# /etc/X11/default-display-manager contained lightdm instead of /usr/sbin/lightdm
	#CUSTOM LightDM - optional & will be empty
	#Edit the following file :

	# Check if the user has requested odd release IE 4.2.1 (non -standard from database)
		# Verify

		# 14.04 + moved files on me
		if [[ -f "${PACKAGE}/etc/lightdm/unity-greeter.conf" ]]; then
			cp "${PACKAGE}/etc/lightdm/unity-greeter.conf" "${PACKAGE}/etc/lightdm/lightdm-gtk-greeter.conf"
			cp "${PACKAGE}/etc/lightdm/unity-greeter.conf" "${PACKAGE}/etc/lightdm/lightdm-gtk-greeter-ubuntu.conf"
		fi

	# POST AND PRE-INST Files.
	cp "/usr/share/ultimate_edition/postinst" "${PACKAGE}/DEBIAN/"
	cp "/usr/share/ultimate_edition/preinst" "${PACKAGE}/DEBIAN/"

	# Plymouth Stamping - now done through "alternatives" in preinst

	# Distro Templates
	# Software Center - Skin it with a dark theme

	# Software Center Icon Stamping

	if [[ -d "/usr/share/ultimate_edition/skel/" && -d "${PACKAGE}/etc/" ]]; then
		cp -R "/usr/share/ultimate_edition/skel/" "${PACKAGE}/etc/" 2>/dev/null
	else
		Error "Critical: No skelaton present or missing ${PACKAGE}/etc/"
		exit 1;
	fi

	if [[ -f "${PACKAGE}/etc/skel/.face" ]]; then
		Encapsulate "Setting up /etc/skel: Success"
	else
		Encapsulate "Setting up /etc/skel: Failure."
	fi

	#Compiz
	Encapsulate "Setting the compiz settings logo for ${SHORTVERSION}"
	if [[ -f "${PACKAGE}/etc/skel/.config/compiz-1/compizconfig/Default.ini" ]]; then
		sed -i "s/#NUMBER/${SHORTVERSION}/g" "${PACKAGE}/etc/skel/.config/compiz-1/compizconfig/Default.ini"
	else
		Error "Missing file: ${PACKAGE}/etc/skel/.config/compiz-1/compizconfig/Default.ini"
	fi

	# Setup Theme distribution specific:
	if [[ -f "${PACKAGE}/etc/skel/.gconf/apps/metacity/general/%gconf.xml" ]]; then
		sed -i "s/#THEMENAME/Ultimate Edition ${SHORTVERSION}/g" "${PACKAGE}/etc/skel/.gconf/apps/metacity/general/%gconf.xml"
		Encapsulate "Setting up Theme specific to ${SHORTVERSION}: Success."
	fi

	# Set Firefox distribution specific:
	if ! [[ "${MSERVER}" ]]; then
		if [[ -f "${PACKAGE}/etc/skel/.mozilla/firefox/q2l51o82.default/prefs.js" ]]; then
			sed -i "s/#VERSION/${LONGVERSION}/g" "${PACKAGE}/etc/skel/.mozilla/firefox/q2l51o82.default/prefs.js"
			sed -i "s/#ARCH/${ARCH}/g" "${PACKAGE}/etc/skel/.mozilla/firefox/q2l51o82.default/prefs.js"
			Encapsulate "Setting up mozilla firefox specific to ${LONGVERSION}: Success."
		fi
	fi

	# Create ORIGIN - aditional core files
{
	echo 'Vendor: Ultimate Edition'
	echo 'Vendor-URL: http://www.ultimateedition.info/'
	echo 'Bugs: https://launchpad.net/ubuntu.ultimate/+filebug'
	echo 'Parent: Ubuntu'
} > "${PACKAGE}/etc/dpkg/origins/${DIST_NAME}"
	# Requested additional DE(s)?
	DEBTYPE=""
	COMMANDISSUED=$(echo "$@" | tr '[:upper:]' '[:lower:]')
	SETDEFAULT=$(echo "${COMMANDISSUED}" | grep -i "defaultde=")
	if [[ "${SETDEFAULT}" ]]; then
		DEFAULTDE=$(echo "${COMMANDISSUED}" | grep -i "defaultde=" | sed "s/^.*defaultde=//g" | cut -d" " -f1)
		if [[ "${DEFAULTDE}" ]]; then
			Encapsulate "Default Desktop Environment (DE) specified as: ${DEFAULTDE}, adjusting accordingly."
		fi
	fi
	INFOLDER="${PWD}"
	if [[ "${DEBUG}" ]]; then
		echo "DEBUG: IN ${INFOLDER}"
	fi

	if [[ -d "${PACKAGE}/etc/skel/" ]]; then
		cd "${PACKAGE}/etc/skel/" || exit 1
	fi

	# Snatch additional DE's?
	for EACH in "$@"
	do
		CHECKIT=$(echo "${EACH}" | tr '[:lower:]' '[:upper:]')
		for OPTIONAL in "${EXTRADE[@]}"
		do
			if [[ "${CHECKIT}" == "${OPTIONAL}" ]]; then
				CHECKIT=$(echo "${EACH}" | tr '[:upper:]' '[:lower:]')
				if [[ -f "/usr/share/ultimate_edition/configs/${CHECKIT}.tar.gz" ]]; then
					Encapsulate "Installing environmental support for ${CHECKIT}"
					# I went through hell for the below, hidden files are a chore to deal with in bash.  Won't play, just fix it later.
					#shopt -s dotglob
					Encapsulate "Source: /usr/share/ultimate_edition/configs/${CHECKIT}.tar.gz Dest: ${PACKAGE}/etc/skel/"
					cp "/usr/share/ultimate_edition/configs/${CHECKIT}.tar.gz" .
	#				# Turn it back off..
					#shopt -u dotglob
					Encapsulate "Extracting, ${CHECKIT}.tar.gz"
					if [[ -f "${CHECKIT}.tar.gz" ]]; then
						tar xf "${CHECKIT}.tar.gz"
						rm -f "${CHECKIT}.tar.gz"
					fi
				else
					Encapsulate "Full support for ${CHECKIT}, has not been created yet. E-Mail TheeMahn <theemahn@gmail.com>"
				fi
			fi
		done
	done
	cd "${INFOLDER}" || exit 1

	# Currently we on care about one...
	if [[ "${DEFAULTDE}" ]]; then
		Encapsulate "Setting defaultde as ${DEFAULTDE} in /etc/skel."
		if [[ -f "/usr/share/ultimate_edition/configs/${DEFAULTDE}.tar.gz" ]]; then
			cp "/usr/share/ultimate_edition/configs/${DEFAULTDE}.tar.gz" "${PACKAGE:?}/etc/skel"
			CD="${PWD}" || exit 1
			cd "${PACKAGE}/etc/skel/" || exit 1
			SUPPRESS=$(tar xf "${DEFAULTDE}.tar.gz")
			SUPPRESS=$(rm "${DEFAULTDE}.tar.gz")
			Encapsulate "Success: settings for ${DEFAULTDE} set."
			cd "$CD" || exit 1
		else
			Encapsulate "Error: /usr/share/ultimate_edition/configs/${DEFAULTDE}.tar.gz not found."
		fi
	fi
	Encapsulate "Setting up base files for ${PACKAGE}."
	cp -R /usr/share/ultimate_edition/uebuilder/* "${PACKAGE:?}/usr/share/"
	Encapsulate "Setting up root based files for ${PACKAGE}."
	if [[ -d "/usr/share/ultimate_edition/root/" ]]; then
		cp -R /usr/share/ultimate_edition/root/* "${PACKAGE:?}/"
	fi
	# Clean up any straglers - last line of hope for success.  Break out an arrays - we don't play.
	# Store where we came in.
	INDIRECTORY="${PWD}"
	# Roll to the skelaton we are building
	if [[ -d "${PACKAGE:?}/" ]]; then
		cd "${PACKAGE:?}/" || exit 1
	fi

	# IT IS NOW ON LIKE DONKEY KONG. We will strip tough 100,000 lines of code if necessary
	# looking for an error I may have made, I am human & prone to error. Break
	# out a nested loop in multiple arrays.
	declare -a TYPES=("#ULTIMATE_WALLPAPER" "#ULTIMATE_THEME" "#VERSION" "#NUMBER" "#DOTTED" "#THEMENAME" "#ULTIMATE_LOGO");
	declare -a REPLACEMENT=("Ultimate_Edition_${CVERSION}" "Ultimate Edition ${CVERSION}" "${CVERSION}" "${CVERSION}" "ultimate.edition.${CVERSION}" "Ultimate Edition ${CVERSION}" "${CVERSION}-logo");
	Center "Pushing core to replicate settings for ${SHORTVERSION}. Stage 1"
	ARRAY=0
	for ITEM in "${TYPES[@]}"
	do
		FILETOPROCESS=$(grep -r "#${ITEM}" | cut -d ":" -f1)
		for EACH in "${FILETOPROCESS[@]}"
		do
			#echo "ARRAY:$ARRAY"
			REPLACE="${REPLACEMENT[$ARRAY]}"
			if [[ "${DEBUG}" ]]; then
                echo "${EACH} contains a reference to ${ITEM}, setting for ${SHORTVERSION}."
			    echo "Item:${ITEM} Replacement:${REPLACE} File:${EACH} in ${PWD}"
            fi
			SUPRESS=$(sed -i "s/#${ITEM}/${REPLACE}/g" "${EACH}" 2>/dev/null)
		done
	ARRAY=$((ARRAY + 1))
	done
	shopt -s nullglob
	declare -a FILETOPROCESS=();
	declare -a TYPES=("#ULTIMATE_WALLPAPER" "#ULTIMATE_THEME" "#VERSION" "#NUMBER" "#DOTTED" "#THEMENAME" "#ULTIMATE_LOGO" "#DTYPE");
	declare -a REPLACEMENT=("Ultimate_Edition_${SHORTVERSION}" "Ultimate Edition ${SHORTVERSION}" "${SHORTVERSION}" "${SHORTVERSION}" "ultimate.edition.${SHORTVERSION}" "Ultimate Edition ${SHORTVERSION}" "${SHORTVERSION}-logo" "${DTYPE}" );
	Center "Pushing core to replicate settings for ${CVERSION}. Stage 2"
	INDEX=0
	for ITEM in "${TYPES[@]}"
	do
		if [[ "${DEBUG}" ]]; then
            echo "DEBUGGING in ${PWD}"
        fi
        Encapsulate "Searching: ${ITEM} | Replacing with: ${REPLACEMENT[$INDEX]}"
        ( shopt -s globstar dotglob;
        for file in **; do
            if [[ -f "${file}" ]] && [[ -w "${file}" ]]; then
                sed -i -- "s/${ITEM}/${REPLACEMENT[$INDEX]}/g" "${file}"
            fi
        done
        )
        #find . -type f -exec sed -i "s/${ITEM}/${REPLACEMENT[$INDEX]}/g" {} +
        #find . -exec sed -i -e "s/${ITEM}/${REPLACEMENT[$INDEX]}/g" {} \;
#		SUPPRESS=$(find ./ -type f -exec sed -i "s/${ITEM}/${REPLACEMENT[$INDEX]}/g" {})
        INDEX=$(( INDEX + 1 ))
	done
    if [[ "${DEBUG}" ]]; then
        echo "DEBUGGING in ${PWD}"
        cat .config/kdeglobals
    fi
	FullBar
	# Go back we are done.
	if [[ -d "${INDIRECTORY}" ]]; then
		cd "${INDIRECTORY}" || exit 1
	fi

	## Deceptive casper fs user and host.
	#Encapsulate "Creating Casper user."
	#echo 'export USERNAME="ultimate"' > "${PACKAGE}/etc/casper.conf"
	#echo 'export USERFULLNAME="Live session user"' >> "${PACKAGE}/etc/casper.conf"
	#echo 'export HOST="ultimate"' >> "${PACKAGE}/etc/casper.conf"
	#echo 'export BUILD_SYSTEM="Ultimate Edition"' >> "${PACKAGE}/etc/casper.conf"

	# Hostname
	Encapsulate "Setting Hostname to ultimate."
	echo "ultimate" > "${PACKAGE}/etc/hostname"

	# Generate Control file for debian packaging.
	Encapsulate "Creating control file."
	# Create CONTROL FILE
{
	echo "Package: ${PACKAGENAME}"
	echo "Version: ${2}"
	echo "Essential: yes"
	echo 'Architecture: all'
	echo 'Maintainer: UE Team <theemahn@ultimateedition.info>'
	echo 'Installed-Size: 5104'
	echo "Depends: base-files"
}  > "${PACKAGE}/DEBIAN/control"
{
	echo "Replaces: ultimate-edition-${SHORTVERSION}-${DTYPE}-core-files, lsb-base, base-files, lsb-release, gnome-system-monitor, mate-desktop-environment-core, mate-system-monitor, mate-system-monitor, mate-system-monitor-common, base-files, bash, unity-greeter, metacity-common, gsettings-desktop-schemas, nautilus-data, ultimate-edition-customizations, ${PACKAGENAME}, ${REPLACEMENTVER}, mate-desktop-common, network-manager, network-manager-gnome, ubiquity, xubuntu-default-settings, lightdm-gtk-greeter, caja-common, marco-common, mate-panel, mate-control-center-common, mate-control-center, pluma-common, mate-desktop-environment, plymouth-theme-ubuntu-text, casper, budgie-desktop-environment, budgie-desktop-common, kubuntu-settings-desktop, ubuntu-mate-default-settings, console-setup, apache2, ubiquity-frontend-kde, ubiquity-frontend-gtk, awstats, vsftpd, openssh-client, procps, plasma-workspace, lsb-release, gerbera, kubuntu-default-settings, kwin-data, postfix, plasma-workspace-data, grub, grub2"
	echo "Section: web"
	echo "Homepage: ${HOMEPAGE}"
	echo "Priority: optional"
	echo "Description: Ultimate Edition base files"
	echo " Ultimate Edition ${DIST} specific distribution defaults. This package"
	echo " was auto-generated using TheeMahns O/S Builder (uecorebuilder)."
} >> "${PACKAGE}/DEBIAN/control"
	#if [[ -f /usr/share/applications/mate-about.desktop ]]; then
	if [[ -f "${PACKAGE:?}/etc/apache2/conf-available/security.conf" ]]; then
		Encapsulate "Setting initial server security."
		#echo -n 'SecServerSignature "' >> "${PACKAGE:?}/etc/apache2/conf-available/security.conf"
		#echo "${OUTDISTRO// /_}\"" >> "${PACKAGE:?}/etc/apache2/conf-available/security.conf"
		if [[ -f "${PACKAGE:?}/etc/apache2/conf-available/security.conf" ]]; then
			if [[ -d "${PACKAGE:?}/etc/apache2/conf-enabled/" ]]; then
				INFOLDER="${PWD}"
				cd "${PACKAGE:?}/etc/apache2/conf-enabled/" || exit 1;
				Encapsulate "Symbolically linking security file to be enabled."
				ln -s "../conf-available/security.conf" security.conf
				cd "${INFOLDER}" || exit 1;
			fi
		else
			Error "${PACKAGE:?}/etc/apache2/conf-available/security.conf does not exist."
		fi
		if [[ -f "${PACKAGE:?}/var/www/html/index.html" ]]; then
			Encapsulate "Adjusting default homepage for Apache2"
			sed -i "s/SERVERTYPE/${OUTDISTRO}/g" "${PACKAGE:?}/var/www/html/index.html"
			COMMAND="$*"
			sed -i "s/COMMAND/${COMMAND}/g" "${PACKAGE}//var/www/html/index.html"
		fi
	fi

	#Set Wallpaper
	if ! [[ "${MSERVER}" ]]; then
		# MATE
		if [[ -f "${PACKAGE}/usr/share/glib-2.0/schemas/org.mate.background.gschema.xml" ]]; then
			sed -i "s/#WALLPAPER/Ultimate_Edition_${SHORTVERSION}.png/g" "${PACKAGE}/usr/share/glib-2.0/schemas/org.mate.background.gschema.xml"
		fi
		# Budgie
		if [[ -f "${PACKAGE}/usr/share/glib-2.0/schemas/15_budgie-desktop-environment.gschema.override" ]]; then
			sed -i "s/#WALLPAPER/Ultimate_Edition_${SHORTVERSION}.png/g" "${PACKAGE}/usr/share/glib-2.0/schemas/15_budgie-desktop-environment.gschema.override"
		fi
	fi
	#SET LOGIN:
	if ! [[ "${MSERVER}" ]]; then
			#Wallpaper
			Encapsulate "Setting the default wallpaper as Ultimate_Edition_${SHORTVERSION}.png"
			if [[ -f "${PACKAGE}/usr/share/glib-2.0/schemas/com.canonical.unity-greeter.gschema.xml" ]]; then
				sed -i "s/#WALLPAPER/Ultimate_Edition_${SHORTVERSION}.png/g" "${PACKAGE}/usr/share/glib-2.0/schemas/com.canonical.unity-greeter.gschema.xml"
			fi

			#Set Unity greeter splash
			Encapsulate "Setting the default Unity Greeter wallpaper as Ultimate_Edition_${SHORTVERSION}.png"
			if [[ -f "${PACKAGE}/usr/share/glib-2.0/schemas/com.canonical.unity-greeter.gschema.xml" ]]; then
				sed -i "s/#VERSION/${SHORTVERSION}/g" "${PACKAGE}/usr/share/glib-2.0/schemas/com.canonical.unity-greeter.gschema.xml"
			fi

			#THEMENAME
			Encapsulate "Setting the default theme as Ultimate_Edition_${SHORTVERSION}"
			if [[ -f "${PACKAGE}/usr/share/glib-2.0/schemas/com.canonical.unity-greeter.gschema.xml" ]]; then
				sed -i "s/#THEMENAME/Ultimate Edition ${SHORTVERSION}/g" "${PACKAGE}/usr/share/glib-2.0/schemas/com.canonical.unity-greeter.gschema.xml"
			fi

			#LIGHTDM
			Encapsulate "Setting the default LightDM theme as Ultimate_Edition_${SHORTVERSION}"
			if [[ -f "${PACKAGE}/usr/share/glib-2.0/schemas/mate-ubuntu.gschema.override" ]]; then
				sed -i "s/#WALLPAPER/Ultimate_Edition_${SHORTVERSION}.png/g" "${PACKAGE}/usr/share/glib-2.0/schemas/mate-ubuntu.gschema.override"
				sed -i "s/#WALLPAPER/Ultimate_Edition_${SHORTVERSION}.png/g" "${PACKAGE}/usr/share/glib-2.0/schemas/mate-ubuntu.gschema.override"
				sed -i "s/#WALLPAPER/Ultimate_Edition_${SHORTVERSION}.png/g" "${PACKAGE}/usr/share/glib-2.0/schemas/mate-ubuntu.gschema.override"
				sed -i "s/#THEMENAME/Ultimate Edition ${SHORTVERSION}/g" "${PACKAGE}/usr/share/glib-2.0/schemas/mate-ubuntu.gschema.override"
				sed -i "s/#WALLPAPER/Ultimate_Edition_${SHORTVERSION}.png/g" "${PACKAGE}/usr/share/glib-2.0/schemas/mate-ubuntu.gschema.override"
				sed -i "s/#THEMENAME/Ultimate Edition ${SHORTVERSION}/g" "${PACKAGE}/usr/share/glib-2.0/schemas/mate-ubuntu.gschema.override"
				sed -i "s/#VERSION/${SHORTVERSION}/g" "${PACKAGE}/usr/share/glib-2.0/schemas/mate-ubuntu.gschema.override"
			fi

			#Compiz
			Encapsulate "Setting the compiz settings logo for Ultimate_Edition_${SHORTVERSION}"
			if [[ -f "${PACKAGE}/etc/skel/.config/compiz-1/compizconfig/Default.ini" ]]; then
				sed -i "s/#NUMBER/${SHORTVERSION}/g" "${PACKAGE}/etc/skel/.config/compiz-1/compizconfig/Default.ini"
			else
				Error "Missing file: ${PACKAGE}/etc/skel/.config/compiz-1/compizconfig/Default.ini"
			fi

			#VERSION Control
			Encapsulate "Entering Version control for ${SHORTVERSION}"
			if [[ -f "${PACKAGE}/usr/share/glib-2.0/schemas/mate-ubuntu.gschema.override" ]]; then
				sed -i "s/#WALLPAPER/Ultimate_Edition_${SHORTVERSION}.png/g" "${PACKAGE}/usr/share/glib-2.0/schemas/com.canonical.unity-greeter.gschema.override"
				sed -i "s/#VERSION/${SHORTVERSION}/g" "${PACKAGE}/usr/share/glib-2.0/schemas/com.canonical.unity-greeter.gschema.override"
				sed -i "s/#THEMENAME/Ultimate Edition ${SHORTVERSION}/g" "${PACKAGE}/usr/share/glib-2.0/schemas/com.canonical.unity-greeter.gschema.override"
				sed -i "s/#VERSION/${SHORTVERSION}/g" "${PACKAGE}/usr/share/glib-2.0/schemas/com.canonical.unity-greeter.gschema.override"
				sed -i "s/#WALLPAPER/Ultimate_Edition_${SHORTVERSION}.png/g" "${PACKAGE}/usr/share/glib-2.0/schemas/com.canonical.unity-greeter.gschema.override"
				sed -i "s/#THEMENAME/Ultimate Edition ${SHORTVERSION}/g" "${PACKAGE}/usr/share/glib-2.0/schemas/com.canonical.unity-greeter.gschema.override"
			fi

			#THEMENAME
			if [[ -f "${PACKAGE}/usr/share/glib-2.0/schemas/mate-ubuntu.gschema.override" ]]; then
				Encapsulate "Setting Theme name to: Ultimate Edition ${SHORTVERSION}"
				sed -i "s/#THEMENAME/Ultimate Edition ${SHORTVERSION}/g" "${PACKAGE}/usr/share/glib-2.0/schemas/mate-ubuntu.gschema.override"
			fi

			#GTK
			if [[ -f "${PACKAGE}/etc/skel/.config/gtk-3.0/settings.ini" ]]; then
				Encapsulate "Setting theme as Ultimate Edition ${SHORTVERSION}"
				sed -i "s/#THEMENAME/Ultimate Edition ${SHORTVERSION}/g" "${PACKAGE}/etc/skel/.config/gtk-3.0/settings.ini"
				sed -i "s/#THEMENAME/Ultimate Edition ${SHORTVERSION}/g" "${PACKAGE}/etc/skel/.gtkrc-2.0"
			else
				Error "Missing file: ${PACKAGE}/etc/skel/.config/gtk-3.0/settings.ini"
			fi

			#GTK Settings
			if [[ -f "${PACKAGE}/etc/skel/.gtkrc-2.0-kde4" ]]; then
				sed -i "s/#THEMENAME/Ultimate Edition ${SHORTVERSION}/g" "${PACKAGE}/etc/skel/.gtkrc-2.0-kde4"
			else
				Error "Missing file: ${PACKAGE}/etc/skel/.gtkrc-2.0-kde4"
			fi

			#Dist specific files
			if [[ -f "/usr/share/ultimate_edition/dist-specific/${SHORTVERSION}" ]]; then
				Encapsulate "Checking for distibution specific files: Found & transfering to deb."
				cp -f "/usr/share/ultimate_edition/dist-specific/${SHORTVERSION}" "${PACKAGE}/etc/skel/.config/dconf/"
				mv "${PACKAGE}/etc/skel/.config/dconf/${SHORTVERSION}" "${PACKAGE}/etc/skel/.config/dconf/user"
			else
				Encapsulate "${SHORTVERSION} does not exist setting 4.2 as default."
				Encapsulate "Please report this error to theemahn <theemahn@os-builder.com>"
				cp "/usr/share/ultimate_edition/dist-specific/4.2" "${PACKAGE}/etc/skel/.config/dconf/user"
			fi
	fi

	#Unity Greeter
	Encapsulate "Setting up auto login for ${DIST_NAME_LONG}. in ${PWD} working on ${PACKAGE}"
	if [[ -f "/usr/share/ultimate_edition/root/usr/share/glib-2.0/schemas/90_unity-greeter.gschema.override" ]]; then
		Encapsulate "Found internal unity greeter copying."
		cp /usr/share/ultimate_edition/root/usr/share/glib-2.0/schemas/90_unity-greeter.gschema.override "${PACKAGE}/usr/share/glib-2.0/schemas/90_unity-greeter.gschema.override"
	fi
	if [[ -f "${PACKAGE}/usr/share/glib-2.0/schemas/90_unity-greeter.gschema.override" ]]; then
		Encapsulate "Setting up Unity Greeter for ${DIST_NAME_LONG}."
		sed -i "s/#LOGO/logo-${SHORTVERSION}/g" ${PACKAGE}/usr/share/glib-2.0/schemas/90_unity-greeter.gschema.override
		sed -i s/#WALLPAPER/Ultimate_Edition_${SHORTVERSION}/g "${PACKAGE}/usr/share/glib-2.0/schemas/90_unity-greeter.gschema.override"
		if [[ "${DEBUG}" ]]; then
			echo "DEBUGGING: ${PACKAGE}/usr/share/glib-2.0/schemas/90_unity-greeter.gschema.override:"
			cat "${PACKAGE}/usr/share/glib-2.0/schemas/90_unity-greeter.gschema.override"
		fi
	else
		Error "Unity Greeter Override is missing."
	fi
	if [[ -f "/usr/share/ultimate_edition/00_site_settings" ]]; then
		mkdir -p "${PACKAGE}/etc/dconf/db/site.d/"
		SUPPRESS=$(cp "/usr/share/ultimate_edition/00_site_settings" "${PACKAGE}/etc/dconf/db/site.d/")
		sed -i "s/#WALLPAPER/Ultimate_Edition_${LONGVERSION}.png/g" "${PACKAGE}/etc/dconf/db/site.d/00_site_settings"
		sed -i "s/#THEMENAME/Ultimate Edition ${LONGVERSION}/g" "${PACKAGE}/etc/dconf/db/site.d/00_site_settings"
		sed -i "s/#VERSION/${LONGVERSION}/g" "${PACKAGE}/etc/dconf/db/site.d/00_site_settings"
		if ! [[ "${SUPPRESS}" ]]; then
			Encapsulate "Setting sitewide settings: Done."
		else
			Encapsulate "Setting sitewide settings: Failure."
		fi
	fi

	#THEME
	if [[ -f "/usr/share/ultimate_edition/00_site_settings" ]]; then
		mkdir -p "${PACKAGE}/etc/dconf/db/site.d/"
		SUPPRESS=$(cp "/usr/share/ultimate_edition/00_site_settings" "${PACKAGE}/etc/dconf/db/site.d/")
		sed -i "s/#WALLPAPER/Ultimate_Edition_${LONGVERSION}.png/g" "${PACKAGE}/etc/dconf/db/site.d/00_site_settings"
		sed -i "s/#THEMENAME/Ultimate Edition ${LONGVERSION}/g" "${PACKAGE}/etc/dconf/db/site.d/00_site_settings"
		sed -i "s/#VERSION/${LONGVERSION}/g" "${PACKAGE}/etc/dconf/db/site.d/00_site_settings"
		if ! [[ "${SUPPRESS}" ]]; then
			Encapsulate "Setting sitewide settings: Done."
		else
			Encapsulate "Setting sitewide settings: Failure."
		fi
	fi
	# If this file exists from Ubuiquity package exists installation will fail, a
	# workagound is to touch the object and pre-requiste a replaces ubiquity in the
	# control file.
	Encapsulate "Fixing Installation halt."
	touch "${PACKAGE}/usr/lib/ubiquity/apt-setup/generators/40cdrom"

	# Set networking as automanaged. Fixed 5.0+?
	#Encapsulate "Repairing networking issues."
	#mkdir -p "${PACKAGE}/etc/NetworkManager/"
	#echo "[main]" > "${PACKAGE}/etc/NetworkManager/NetworkManager.conf"
	#echo "plugins=ifupdown,keyfile,ofono" >> "${PACKAGE}/etc/NetworkManager/NetworkManager.conf"
	#echo "dns=dnsmasq" >> "${PACKAGE}/etc/NetworkManager/NetworkManager.conf"
	#echo "" >> "${PACKAGE}/etc/NetworkManager/NetworkManager.conf"
	#echo "[ifupdown]" >> "${PACKAGE}/etc/NetworkManager/NetworkManager.conf"
	#echo "managed=true" >> "${PACKAGE}/etc/NetworkManager/NetworkManager.conf"

	# Set startup application network manager, no show in KDE, it has it's own.
	#if ! [[ "$MINIMAL" ]]; then
	#	echo "[Desktop Entry]" > "${PACKAGE}/etc/xdg/autostart/nm-applet.desktop"
	#	echo "Name=Network" >> "${PACKAGE}/etc/xdg/autostart/nm-applet.desktop"
	#	echo "Comment=Manage your network connections" >> "${PACKAGE}/etc/xdg/autostart/nm-applet.desktop"
	#	echo "Icon=nm-device-wireless" >> "${PACKAGE}/etc/xdg/autostart/nm-applet.desktop"
	#	echo "Exec=nm-applet" >> "${PACKAGE}/etc/xdg/autostart/nm-applet.desktop"
	#	echo "Terminal=false" >> "${PACKAGE}/etc/xdg/autostart/nm-applet.desktop"
	#	echo "Type=Application" >> "${PACKAGE}/etc/xdg/autostart/nm-applet.desktop"
	#	echo "NoDisplay=true" >> "${PACKAGE}/etc/xdg/autostart/nm-applet.desktop"
	#	echo "NotShowIn=KDE;" >> "${PACKAGE}/etc/xdg/autostart/nm-applet.desktop"
	#	echo "X-GNOME-Bugzilla-Bugzilla=GNOME" >> "${PACKAGE}/etc/xdg/autostart/nm-applet.desktop"
	#	echo "X-GNOME-Bugzilla-Product=NetworkManager" >> "${PACKAGE}/etc/xdg/autostart/nm-applet.desktop"
	#	echo "X-GNOME-Bugzilla-Component=nm-applet" >> "${PACKAGE}/etc/xdg/autostart/nm-applet.desktop"
	#	echo "X-GNOME-UsesNotifications=true" >> "${PACKAGE}/etc/xdg/autostart/nm-applet.desktop"
	#	echo "X-Ubuntu-Gettext-Domain=nm-applet" >> "${PACKAGE}/etc/xdg/autostart/nm-applet.desktop"
	#fi

	# Change in LightDM 16.04+
	FILEOUT="${PACKAGE}/etc/lightdm/lightdm-gtk-greeter.conf.d/99_ultimate-edition.conf"
{
	echo "[greeter]"
	echo "background=${QUOTE}/usr/share/wallpapers/Ultimate_Edition_${DIST_VERSION}.png${QUOTE}"
	echo "theme-name=${QUOTE}${DIST_NAME} ${SHORTVERSION}${QUOTE}"
	echo "icon-theme-name=${QUOTE}${DIST_NAME} Dark Glass${QUOTE}"
	echo "font-name=Liberation Sans Serif 11"
	echo "xft-antialias=true"
	echo "xft-dpi=96"
	echo "xft-hintstyle=full"
	echo "xft-rgba=rgb"
	echo "indicators=~host;~spacer;~clock;~spacer;~session;~a11y;~language;~power"
	echo "keyboard=onboard"
	echo "reader=orca"
	echo "position = 50%,center 50%,center"
	echo "default-user-image = #avatar-default"
	echo "a11y-states=contrast;font;keyboard;reader"
	echo "user-background = false"
	echo "clock-format = %a %d %b, %H:%M"
	echo "active-monitor=0"
} > "${FILEOUT}"
	if [[ -f "${PACKAGE}/etc/apache2/conf-available/security.conf" ]]; then
		#declare -a SERVEROPTIONS=("SQL" "FTP" "WORDPRESS" "APACHE" "PHP" "AWSTATS" "MONITOR");

		#declare -a SERVERPACKAGES=("mysql-server" "vsftpd" "wordpress" "apache2,libapache2-mod-security2, libapache2-modsecurity, libapache2-mod-evasive" "php5, libapache2-mod-php5, php5-mcrypt" "awstats, libgeo-ipfree-perl, libnet-ip-perl" "vnstat,htop,bmon,nload,iftop,iptraf,nethogs,slurm,tcptrack,cbm,speeometer");
		INDEX=0
		for EACHOPTION in "${SERVEROPTIONS[@]}"
		do
			GREPIT=$(echo "$*" | grep -i "${EACHOPTION}")
			if ! [[ "${GREPIT}" ]]; then
				PACKAGES+="${SERVERPACKAGES[$INDEX]},"
			fi
			((INDEX + 1))
		done
		PACKAGES="${PACKAGES//,$/}"
		#PACKAGES=$(echo "${PACKAGE}S" | sed 's/,$//')
		Encapsulate "Server detected, injecting depends line."
		if [[ -f "${PACKAGE}/etc/apache2/conf-available/security.conf" ]]; then
			Encapsulate "Manipulating Apache2"
			Encapsulate "Setting Server Security mod line to: ${OUTDISTRO}"
			sed -i "s/#BUILD/${OUTDISTRO}/g" "${PACKAGE}/etc/apache2/conf-available/security.conf"
			MANIPULATED=$(sed -n "/${OUTDISTRO}/p" "${PACKAGE}/etc/apache2/conf-available/security.conf")
			if [[ "${MANIPULATED}" ]]; then
				Encapsulate "Success."
			else
				Error "Failure: Maniputulating custom server string."
			fi
		else
			Error "No Apache configuration security file."
		fi
		#echo "Depends: ${PACKAGE}S" >> "${PACKAGE}/DEBIAN/control"
	fi

	if [[ "${MSERVER}" ]]; then
		Encapsulate "Scrapping the skelaton this is a minimal server."
		rm -R "${PACKAGE:?}/etc/skel/" 2>/dev/null
		if [[ -f "${PACKAGE}/usr/share/applications/ubuntu-about.desktop" ]]; then
			rm -f "${PACKAGE}/usr/share/applications/ubuntu-about.desktop"
		fi
		Encapsulate "Setting special post installation script for minimal server"
		SUPPRESS=$(cp "/usr/share/ultimate_edition/postinst.mserver" "${PACKAGE}/DEBIAN/postinst")
	fi
	#if ! [[ "${MSERVER}" || "${SERVER}" ]]; then
	#	rm -R "${PACKAGE:?}/var/"
	#fi

    if [[ -f "${PACKAGE:?}/etc/sddm.conf" ]]; then
        Encapsulate "Modifying sddm for theme."
        sed -i "s/#VERSION/${LONGVERSION}/g" "${PACKAGE:?}/etc/sddm.conf"
    else
        Error "SDDM not found. Minimal Server?"
    fi
	Encapsulate "Populating documentation for ${PACKAGE}."
	cp "/usr/share/ultimate_edition/doc/copyright" "${PACKAGE}/usr/share/doc/${PACKAGE}/"
	cp "/usr/share/ultimate_edition/doc/changelog.gz" "${PACKAGE}/usr/share/doc/${PACKAGE}/"
	if [[ -d "${PACKAGE}" ]]; then
		CURRENT="${PWD}"
		if [[ -d "${PACKAGE}/etc/" ]]; then
			Encapsulate "Scanning /etc to build conffiles."
			cd "${PACKAGE}" || exit 1
			find etc/ -name "*" -type f > DEBIAN/conffiles
			#search and replace etc/ with /etc/
			sed -i "s/etc/\\/etc/g" DEBIAN/conffiles
			cd "${CURRENT}" || exit 1
		else
			Encapsulate "No /etc/ so need to build conffiles."
		fi
		cd "${PACKAGE}" || exit 1
		Encapsulate "Calculating MD5SUMS in ${PACKAGE}"
		find . -name "DEBIAN" -prune -o -type f -exec md5sum {} + > DEBIAN/md5sums
		if [[ -d "${CURRENT}" ]]; then
			cd "${CURRENT}" || exit 1;
		fi
		Encapsulate "Setting ownership to root in ${PACKAGE}"
		sudo chown -R root:root "${PACKAGE}"
		sudo find "${PACKAGE}" -type d -exec chmod 755 {} \;
		Encapsulate "Chmodding folders to 755: Success."
		#set 644 for files
		sudo find "${PACKAGE}" -type f -exec chmod 644 {} \;
		Encapsulate "Chmodding files to 644: Success."
		Center "Scanning for executables in ${PACKAGE}."
		FullBar

		find "${PACKAGE}" -name "DEBIAN" -prune -o -type f -exec sh -c 'test "$(head -c 2 "${1}")" = "#!"' sh {} \; -print -exec chmod 755 {} \;
		cd "${PACKAGE}/DEBIAN/" || exit 1
		Encapsulate "Setting permissions rights for control etc."
		sudo chmod 755 "./*" 2>/dev/null
		sudo chmod 644 control 2>/dev/null
		sudo chmod 644 md5sums 2>/dev/null
		sudo chmod 644 conffiles 2>/dev/null
		sudo chmod 644 shlibs 2>/dev/null
		sudo chmod 644 symbols 2>/dev/null
		sudo chmod 644 templates 2>/dev/null
		sudo chmod 755 preinst
		sudo chmod 755 postinst
		cd "${CURRENT}" || exit 1
		if [[ -f "${PACKAGE}/etc/update-motd.d/10-help-text" ]]; then
			Encapsulate "Updating Message of the day: Help."
			sudo chmod 755 "${PACKAGE}/etc/update-motd.d/10-help-text"
		fi
		if [[ -f "${PACKAGE}/etc/update-motd.d/01-custom" ]]; then
			Encapsulate "Updating Message of the day: Custom."
			sudo chmod 755 "${PACKAGE}/etc/update-motd.d/01-custom"
		fi
		if [[ -f "${PACKAGE}/etc/update-motd.d/02-conky" ]]; then
			Encapsulate "Updating Message of the day: Conky Info."
			sudo chmod 755 "${PACKAGE}/etc/update-motd.d/02-conky"
		fi
		#sudo chmod 755 ${PACKAGE}/usr/share/applications/ubuntu-about.desktop
		if [[ -d "${PACKAGE:?}/var/www/" ]]; then
			Encapsulate "Setting permissions for web server."
			sudo chown -R www-data:www-data "${PACKAGE:?}/var/www/"
		fi
		if [[ -d "${PACKAGE:?}/var/log/apache2/" ]]; then
			Encapsulate "Setting permissions for web server logging."
			sudo chown -R www-data:www-data "${PACKAGE:?}/var/log/apache2/"
		fi
	else
		Error "CRITICAL ERROR: ${PACKAGE}, not found."
		exit 170;
	fi
	FullBar
	if [[ -d "${PACKAGE}" ]]; then
 		if [[ "${DEBUG}" ]]; then
				echo "Debug: in ${PWD}"
		fi
		Encapsulate "Building Package ${PACKAGENAME}.deb..."
    else
		Error "Critical error in ${PWD} folder ${PACKAGE} does not exist."
		exit 127;
    fi
	if [[ "${REPOSTORM}" ]]; then
		Center "Repostorm detected repairing package if it needs it. Devoked via programmer."
		#repostorm --build "ultimate-edition-${2}-${DEBNAME}-core-files/"
		#repostorm --fix "ultimate-edition-${2}-${DEBNAME}-core-files/"
		#repostorm --build "ultimate-edition-${2}-${DEBNAME}-core-files/"
	else
		Error "Repostorm is not installed, not scanning / fixing errors."
	fi
	if [[ -d "${PACKAGENAME}" ]]; then
       	dpkg --build "${PACKAGENAME}"
	fi
    if [[ -f "${PACKAGENAME}.deb" ]]; then
		Encapsulate "Successfully built: ${PACKAGENAME}.deb"
    else
		Error "Failure building: ${PACKAGENAME}.deb"
		exit 127;
	fi
	if [[ -d "ultimate-edition-${2}-${DEBNAME}-core-files/" ]]; then
	#mv ultimate-edition-core*.deb ultimate-edition-${1}-core-files.deb
		Encapsulate "Cleaning up."
		rm -R "ultimate-edition-${2}-${DEBNAME}-core-files/"
		FullBar
		Center "${APPNAME}(${PROGNAME}): All operations completed successfully."
		FullBar
		if [[ "${REPOSTORM}" ]]; then
			Center "Repostorm detected repairing package if it needs it."
			#repostorm --analyze "ultimate-edition-${2}-${DEBNAME}-core-files.deb"
		else
			Error "Repostorm is not installed, not scanning for errors."
		fi
    else
    	Error "ERROR: Fatal"
		exit 1;
    fi
}


# Help system - I have re-wrote this section to work with code-cleanup.
Help() {
	CONTAINS=$(echo "$@" | grep -w '\-h\|\-\-help')
	if [[ "${DEBUG}" ]]; then
		echo "DEBUGGING HELP FUNCTION: 1:${1} 2:${2} 3:${3} CONTAINS:${CONTAINS}"
	fi
	if ! [[ "${3}" == "" && "${CONTAINS}" ]]; then
		if [[ "${2}" != "" ]]; then
			PRAM="${2}"
		else
			PRAM="ALL"
		fi
	fi
	if [[ "${CONTAINS}" ]]; then
		if [[ "${2}" != "" ]]; then
			PRAM="${2}"
			VersionDump
		else
			PRAM="ALL"
			VersionDump
		fi
	fi
	if ! [[ "${1}" ]]; then
		VersionDump
	fi
	case "${PRAM}" in
		ALL)
		Encapsulate "Usage: ${PROGNAME} -<-COMMAND> [OPTION]"
		FullBar
		Encapsulate "Mandatory arguments to long options are identical for short options."
		Encapsulate "  possible commands..."
		Encapsulate ""
		Encapsulate '  -b       --build         build Ultimate Edition core files'
		Encapsulate '  -h       --help          this help message'
		Encapsulate '  -v       --version       dump version info and exit'
		Encapsulate ""
		FullBar
		Center "${PROGNAME} --help [COMMAND] for further information."
		FullBar;;
		ALL|b|build)
		Encapsulate ""
		Encapsulate "Usage build;"
		FullBar
		Center "${PROGNAME} -b <VERSION>"
		FullBar
		Encapsulate "Invokes ${PROGNAME} to build corefiles for Ultimate Edition <VERSION> from scratch."
		Encapsulate "The format must comply as follows:"
		Encapsulate "<VERSION> [LITE/GAMERS/SERVER] [DE(s)]"
		Encapsulate "Valid arguments are as follows and <REQUIRED>:"
		Encapsulate "Version: 3.4, 3.5 - 5.1"
		Encapsulate "[OPTIONAL TYPES]"
		Encapsulate " "
		Encapsulate "Lite, Gamers, Server, and Minimal-server"
		Encapsulate "[OPTIONAL DE]"
		Encapsulate " "
		Encapsulate "Desktop Environments (DE):"
        INCREMENT=0
        TOTAL="${#EXTRADE[@]}"
		for EACH in "${EXTRADE[@]}";
		do
            INCREMENT=$((INCREMENT+1))
            if [[ "$INCREMENT" != "$TOTAL" ]]; then
    			FULLMONTY="${FULLMONTY} ${EACH}, "
            else
                FULLMONTY="${FULLMONTY} ${EACH}."
            fi
		done
        Encapsulate "${FULLMONTY}"
		Encapsulate "iso, lite, gamers, server and DE's as per synopsis is [OPTIONAL]"
		FullBar
		Encapsulate "Example: ${PROGNAME} --build 5.0 lite xfce mate --defaultde=xfce"
		Encapsulate "Will build core files for Ultimate Edition 5.0 setting xfce as the default (DE)."
		Encapsulate "adding the optional mate DE"
		FullBar;;
		ALL|v|version)
		echo -e "\\n${txtwht}Usage version;${txtrst}"
		echo -e "${txtgrn}${PROGNAME} -v${txtrst}"
		echo -e "Displays ${PROGNAME}'s version number and exits.";;
		ALL|h|help|\?)
		echo -e "\\n${txtwht}Useage Help [COMMAND];${txtrst}"
		echo -e "${txtgrn}${PROGNAME} -h [COMMAND]${txtrst}"
		echo "Displays this message. For futher information ${PROGNAME} help [COMMAND]"
		echo -e "or refer to the manpages.\\n"
		echo -e "man ${PROGNAME}"
		echo -e "${txtgrn}"
		echo -e "Example: ${PROGNAME} -h version"
		echo -e "${txtwht}Will display help about the command version${txtrst}"
	esac
	exit 0
}

shopt -u nullglob
Timer "Start" "${APPNAME}"

case "${1}" in
	-h|--help|-\?) Help "$@"; exit 0;;
	-v|--version) VersionDump "$@"; exit 0;;
	-b|--build) Buildcore "$@"; exit 0;;
	*) Help "$@"; exit 0;;
esac

# ==============================================================================
# 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/
# ==============================================================================
