#!/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 distrobution upgrade fixes everything in round #1
#			Added archeitecture array to scan for supported architectures.
#			Full Power PC and droid support is coming.
#	1.9.5	Added switches to allow customizations while in modify mode.
#
#	1.9.6	Adjusted menu options.
#
#	1.9.7	Closed the LTS (Long Term Supported) Gap.
#	2.0.7	Added initial support for "Jammy Jellyfish" / Ultimate Edition 7.4 & 7.5
# ==============================================================================
# Version Control
APPNAME="TheeMahn O/S Builder"
PROGNAME="tmmount"
VERSION="2.0.7"
BUILDDATE="03/28/2022"
WEBSITE="os-builder.com"
AUTHOR="TheeMahn"
EMAIL="<$AUTHOR@$WEBSITE>"

if [[ -f "ultimate-common" ]]; then
	source ultimate-common
elif [[ -f "/usr/share/ultimate_edition/ultimate-common" ]]; then
	source /usr/share/ultimate_edition/ultimate-common
else
	echo "No Ultimate Edition common source. Please install ultimate-edition-common."
fi
PREREQ="-f -y --allow-unauthenticated"

# Architecture detection routine used below. Declare an integer 0 is off 1 is on
# Boolean if you will.
declare -i ARCHITECTURE

export DEBIAN_FRONTEND=noninteractive
DEBUG=$(echo "$*" | grep -i "debug")
ROOTFOLDER="http://os-builder.com/UETOYS"
THEMEFOLDER="http://os-builder.com/themes"
TMPVAR=$(type -p lsb_release)
RECOMMENDS=$(echo "$@" | grep -i "recommends=")
if [[ "${RECOMMENDS}" ]]; then
	RECOMMENDS=$(echo "$@" | grep -i "recommends=" | sed "s/^.*recommends=//g" | cut -d" " -f1)
else
	# Set default recommends option as yes null if not specified. << - we can expand here ;)
	RECOMMENDS="YES"
fi
if [[ "${TMPVAR}" ]]; then
    DISTREL=$(lsb_release -sr)
elif [[ -f "/etc/os-release" ]]; then
    DISTREL=$(grep -i "version_codename" "/etc/os-release" | cut -d "=" -f2)
fi

declare -a FILELIST=( 'ultimate-edition-os-builder_2.0.5_all.deb' '100-emerald-themes-0.0.1_all.deb' 'any-color-you-like-icon-theme-0.9.4_all.deb' 'apt-fast_0.0.1_all.deb' 'bin2iso_1.9-2_'${ARCH}'.deb' 'boje-themes-1.2.1-all.deb' 'ultimate-edition-conky-builder-1.32_all.deb' 'conky-fonts-0.0.2_all.deb' 'faenza-cupertino-0.0.1_all.deb' 'faenza-darker-0.0.1_all.deb' 'gimp-brushes-1.1.0_all.deb' 'gimp-scripts-2.8.0_all.deb' 'nouvegnomegray-0.0.1_all.deb' 'revolt-0.0.2_all.deb' 'tm-rename-1.0.6_all.deb' 'ultimate-cover-grabber_1.1.1-1_all.deb' 'ultimate-edition-code-cleanup_1.7.4_all.deb' 'ultimate-edition-cursors-0.0.7_all.deb' 'ultimate-edition-female-themes-1.0-all.deb' 'ultimate-edition-icons-baby-blue-0.0.1_all.deb' 'ultimate-edition-icons-dark-glass.0.0.5_all.deb' 'ultimate-edition-multi-monitor_1.7.5_all.deb' 'ultimate-edition-nas-tools_2.0.5_all.deb' 'ultimate-edition-repairtheme-1.7.3-1_all.deb' 'ultimate-edition-sound-scheme-0.0.6_all.deb' 'ultimate-edition-thumbos_1.1.2_all.deb' 'ultimate-edition-user-contributed-wallpapers-1.0_all.deb' 'zoncolor-0.0.1_all.deb' 'zoncolorbrown-0.0.1_all.deb' 'zoncolorgreen-0.0.1_all.deb' 'zoncolorgrey-0.0.1_all.deb' 'zoncolormaroon-0.0.1_all.deb' 'zoncolororange-0.0.1_all.deb' 'zoncolorpink-0.0.1_all.deb' 'zoncolorpurple-0.0.1_all.deb' 'zoncolorred-0.0.1_all.deb' 'zoncolorsilver-0.0.1_all.deb' 'zoncolorsky-0.0.1_all.deb' 'zoncolorslate-0.0.1_all.deb' 'zoncolorturquoise-0.0.1_all.deb' 'zoncolorwhite-0.0.1_all.deb' 'zoncolorxtra-faenzadarkest-0.0.1_all.deb' 'zoncolorxtra-silverfaenzadarkest-0.0.1_all.deb' 'zoncolorxtra-skyfaenzalight-0.0.1_all.deb' 'zoncolorxtra-slatefaenzalight-0.0.1_all.deb' 'pithos_1.4.1-0york1~18.04_all.deb' 'ultimate-edition-roku-ripper-all_1.0.6.deb' 'ultimate-edition-ultimate-network-optimizer-all_1.0.2.deb' );

declare -a INSTALLNAMES=( 'ultimate-edition-os-builder' '100-emerald-themes' 'any-color-you-like-icon-theme' 'apt-fast' 'bin2iso' 'boje-themes' 'ultimate-edition-conky-builder' 'conky-fonts' 'faenza-cupertino-icon-theme' 'faenza-darker-icon-theme' 'gimp-brushes' 'gimp-scripts' 'nouvegnomegray-icon-theme' 'revolt' 'tm-rename' 'ultimate-cover-grabber' 'ultimate-edition-code-cleanup' 'ultimate-edition-cursors' 'ultimate-edition-female-themes-1.0' 'ultimate-edition-icons-dark-glass' 'ultimate-edition-multi-monitor' 'ultimate-edition-nas-tools' 'ultimate-edition-repairtheme' 'ultimate-edition-sound-scheme' 'ultimate-edition-thumbos' 'ultimate-edition-user-contributed-wallpapers' 'zoncolor-icon-theme' 'zoncolorbrown-icon-theme' 'zoncolorgreen-icon-theme' 'zoncolorgrey-icon-theme' 'zoncolormaroon-icon-theme' 'zoncolororange-icon-theme' 'zoncolorpink-icon-theme' 'zoncolorpurple-icon-theme' 'zoncolorred-icon-theme' 'zoncolorsilver-icon-theme' 'zoncolorsky-icon-theme' 'zoncolorslate-icon-theme' 'zoncolorturquoise-icon-theme' 'zoncolorwhite-icon-theme' 'zoncolorxtra-faenzadarkest-icon-theme' 'zoncolorxtra-silverfaenzadarkest-icon-theme' 'zoncolorxtra-skyfaenzalight-icon-theme' 'zoncolorxtra-slatefaenzalight-icon-theme' 'pithos' 'ultimate-edition-roku-ripper' 'ultimate-edition-ultimate-network-optimizer' );

declare -a MALWARE=( 'zeitgeist' );

declare -a MINIMALPACKAGES=( "auditd" "chkrootkit" "command-not-found" "lynis" 'awstats' 'tcpdump' 'nvme-cli' "apt-utils" "hdparm" "dialog" "fail2ban" "nload" "bmon" "slurm" "bwm-ng" "cbm" "speedometer" "vnstat" "ifstat" "dstat" "iftop" "iptraf" "tcptrack" "pktstat" "shellcheck" "openssh-client" "lamp-server^" "nfs-server" "nfs-client" "smbclient" "phpmyadmin" "ssh" "vsftpd" "libapache2-mod-security2" "libapache2-mod-evasive" "net-tools" "mysql-server" "ssh" "fonts-liberation" "mysql-server" "phpmyadmin" "apache2" "fonts-liberation2" "htop" "traceroute" "mtr" "pydf" "mc" "aria2" "nnn" "lftp" "lynx" "siege" "ngrep" "pv" "dstat" "curl" "netcat" "nmap" "openssl" "mutt" "screen" "lsof" "nano" "vim" "iftop" 'openvpn' 'certbot' 'letsencrypt' "mc");

declare -a MINIMALUE=( 'ultimate-edition-os-builder_2.0.5_all.deb' 'apt-fast_0.0.1_all.deb' 'bin2iso_1.9-2_'${ARCH}'.deb' 'ultimate-edition-conky-builder-1.32_all.deb' 'conky-fonts-0.0.2_all.deb' 'tm-rename-1.0.6_all.deb' 'ultimate-cover-grabber_1.1.1-1_all.deb' 'ultimate-edition-code-cleanup_1.7.4_all.deb' 'ultimate-edition-multi-monitor_1.7.5_all.deb' 'ultimate-edition-nas-tools_2.0.5_all.deb' 'ultimate-edition-repairtheme-1.7.3-1_all.deb' 'ultimate-edition-sound-scheme-0.0.6_all.deb' 'ultimate-edition-thumbos_1.1.2_all.deb' 'ultimate-edition-roku-ripper-all_1.0.6.deb' 'ultimate-edition-ultimate-network-optimizer-all_1.0.2.deb' );

declare -a LITEPACKAGES=( "chkrootkit" "command-not-found" "viewnior" 'nvme-cli' 'nano' 'hdparm' 'dialog' 'inxi' 'apt-utils' 'liberation-ttf' 'shellcheck' 'net-tools' 'xinit' 'xserver-xorg' 'udisks' 'gnome-disk-utility' 'gnome-themes-standard' 'broadcom-sta-common' 'ubuntu-restricted-extras' 'p7zip-full' 'alien' 'alsa-oss' 'arj' 'b43-fwcutter' 'bchunk' 'binutils' 'bootchart' 'bum' 'bzip2' 'devede' 'dkms' 'faac' 'faad' 'ffmpeg2theora' 'flac' 'fslint' 'ftp' 'genisoimage' 'gftp' 'gimp' 'glade' 'gnome-codec-install' 'wavpack' 'preload' 'pidgin-plugin-pack' 'unrar' 'mppenc' 'vorbis-tools' 'pidgin-extprefs' 'pidgin-themes' 'xvid4conf' 'gtkpod' 'id3v2' 'hardinfo' 'patchutils' 'qemu' 'python-chm' 'soundkonverter' 'isomaster' 'phatch' 'tidy' 'gnupod-tools' 'pidgin-guifications' 'oss-compat' "simplescreenrecorder" 'rar' 'phatch-cli' 'cabextract' 'gstreamer0.10-fluendo-mp3' 'wireshark' 'pidgin' 'wifi-radar' 'mpg321' 'ntfs-config' 'sysinfo' 'winbind' 'xnest' 'unace' 'htop' 'lintian' 'linux-firmware-nonfree' 'youtube-dl' 'qemuctl' 'qemubuilder' 'broadcom-sta-common' 'imagination' 'terminator' 'vlc' 'gdebi' 'samba' 'clementine' 'mediainfo' 'system-config-samba' 'synaptic' 'xscreensaver-gl-extra' 'xscreensaver-data-extra' 'dconf-tools' 'git' 'subversion' 'cmake' 'gtk3-engine*' 'transmission-gtk' 'firefox' 'hddtemp' 'libreoffice' 'ubuntu-restricted*' 'firefox' 'filezilla' 'flashplugin-installer' 'tovid' 'ethtool' 'mkvtoolnix-gui' 'mkvtoolnix' "pithos" );

declare -a FULLPACKAGES=( "chkrootkit" "command-not-found" "viewnior" "lynis" 'tcpdump' 'nvme-cli'  'nano' 'hdparm' 'dialog' 'inxi' 'apt-utils' 'liberation-ttf' 'net-tools' 'shellcheck' 'xdg-user-dirs-gtk' 'xinit' 'xserver-xorg' 'aisleriot' 'alien' 'alsa-oss' 'arj' 'aspell' 'b43-fwcutter' 'bc' 'bchunk' 'binutils' 'bootchart' 'broadcom-sta-common' 'build-essential' 'bum' 'bzip2' 'bzr' 'cabextract' 'ccd2iso' 'cdparanoia' 'cdrdao' 'cervisia' 'checkgmail' 'cheese' 'clamav' 'clamav-freshclam' 'clamtk' 'clementine' 'cmake' 'cvs' 'dconf-tools' 'dctrl-tools' 'debootstrap' 'devede' 'devscripts' 'dh-buildinfo' 'dkms' 'dvdrip' 'dvdrip-utils' 'dvdstyler' 'dvgrab' 'entagged' 'faac' 'faad' 'fakeroot' 'fancontrol' 'ffmpeg2theora' 'file-roller' 'flac' 'fslint' 'f-spot' 'ftp' 'genisoimage' 'gftp' 'gimp' 'git' 'gnome-codec-install' 'gpp' 'gstreamer0.10-fluendo-mp3' "simplescreenrecorder" 'hardinfo' 'hddtemp' 'htop' 'id3v2' 'imagination' 'isomaster' 'k3b' 'k3b-extrathemes' 'k3d' 'kdeartwork-emoticons' 'kdemultimedia-kio-plugins' 'kdenlive' 'kino' 'kolourpaint4' 'kompare' 'kopete' 'kopete-message-indicator' 'krita' 'ksnapshot' 'ktorrent' 'kvirc' 'libk3b6-extracodecs' 'lintian' 'linux-firmware-nonfree' 'lives' 'lynx' 'mdf2iso' 'mediainfo' 'medit' 'mkvtoolnix' 'mp3gain' 'mpg321' 'mppenc' 'ndisgtk' 'nrg2iso' 'ntfs-config' 'oss-compat' 'oxygen-cursor-theme-extra' 'p7zip' 'p7zip-full' 'phatch' 'phatch-cli' 'preload' 'python-chm' 'python-lxml' 'python-numpy' 'python-pyexiv2' 'python-renderpm' 'python-uniconvertor' 'python-wxversion' 'qemu' 'qemubuilder' 'qemuctl' 'qemu-launcher' 'rar' "simplescreenrecorder" 'ripoff' 'samba' 'sound-juicer' 'soundkonverter' 'squashfs-tools' 'subversion' 'synaptic' 'system-config-samba' 'terminator' 'transmission-gtk' 'tvtime' 'ubuntu-dev-tools' 'unace' 'unrar' 'videotrans' 'vlc' 'vorbisgain' 'vorbis-tools' 'wavpack' 'wifi-radar' 'winbind' 'wireshark' 'xcftools' 'xscreensaver-data-extra' 'xscreensaver-gl-extra' 'xvid4conf' 'firefox' 'libreoffice' 'ubuntu-restricted*' 'kodi' 'virtualbox' 'clementine' 'mc' 'ethtool' 'mkvtoolnix-gui' 'mkvtoolnix' "pithos" "coolretroterm" );

declare -a SERVERPACKAGES=( "auditd" "chkrootkit" "webmin" "command-not-found" "viewnior" "lynis" 'awstats' 'tcpdump' 'nvme-cli' 'nano' 'fail2ban' 'hdparm' 'dialog' 'inxi' 'apt-utils' 'nload' 'bmon' 'slurm' 'bwm-ng' 'cbm' 'speedometer' 'netload' 'vnstat' 'ifstat' 'dstat' 'iftop' 'iptraf' 'tcptrack' 'pktstat' 'netwatch' 'trafshow' 'shellcheck' 'openssh-client' 'lamp-server^' 'nfs-server' 'nfs-client' 'smbclient' 'phpmyadmin' 'ssh'  'apache2' 'vsftpd' 'libapache2-mod-security2' 'libapache2-modsecurity' 'libapache2-mod-evasive' 'liberation-ttf' 'net-tools' 'mysql-server' 'phpmyadmin' 'ssh' 'apache2' 'vsftpd' 'php' 'php7' 'libapache2-mod-php7' 'php7-mcrypt' 'libapache2-mod-security2' 'libapache2-modsecurity' 'libapache2-mod-evasive' 'udisks' 'gnome-disk-utility' 'broadcom-sta-common' 'ubuntu-restricted-extras' 'p7zip-full' 'alsa-oss' 'arj' 'b43-fwcutter' 'bchunk' 'binutils' 'bootchart' 'build-essential' 'bum' 'bzip2' 'bzr' 'cvs' 'dkms' 'faac' 'faad' 'fakeroot' 'ffmpeg2theora' 'flac' 'fslint' 'ftp' 'genisoimage' 'preload' 'debootstrap' 'unrar' 'mppenc' 'vorbis-tools' 'xvid4conf' 'id3v2' 'hardinfo' 'patchutils' 'python-chm' 'dh-buildinfo' 'vorbisgain' 'squashfs-tools' 'gnome-themes-extras' 'tidy' 'oss-compat' 'devscripts' 'rar' 'cabextract' 'gstreamer0.10-fluendo-mp3' 'wireshark' 'ubuntu-dev-tools' 'wifi-radar' 'mpg321' 'gnome-icon-theme-nuovo' 'ntfs-config' 'sysinfo' 'winbind' 'xnest' 'unace' 'htop' 'lintian' 'linux-firmware-nonfree' 'broadcom-sta-common' 'terminator' 'vlc' 'gdebi' 'samba' 'mediainfo' 'system-config-samba' 'synaptic' 'dconf-tools' 'git' 'subversion' 'cmake' 'hddtemp' 'ubuntu-restricted*' 'firefox' 'filezilla' 'flashplugin-installer' 'openvpn' 'certbot' 'letsencrypt' 'iperf3' 'mc' 'ethtool' 'openvpn' 'ca-certificates' 'mkvtoolnix-gui' 'mkvtoolnix' 'libxml-dumper-perl' 'ipmitool' 'smartmontools' 'ipmiutil' 'freeipmi-tools' "pithos" );

declare -a GAMERSPACKAGES=( "chkrootkit" "command-not-found" "viewnior" 'nvme-cli' 'nano' 'dialog' 'inxi' 'apt-utils' 'xdg-user-dirs-gtk' 'xinit' 'xserver-xorg' 'broadcom-sta-common' 'ubuntu-restricted-extras' 'p7zip-full' 'alsa-oss' 'arj' 'b43-fwcutter' 'bzip2' 'conky-all' 'preload' 'unrar' 'xvid4conf' 'rar' 'gstreamer0.10-fluendo-mp3' 'ntfs-config' 'broadcom-sta-common' 'terminator' 'vlc' 'gdebi' 'samba' 'system-config-samba' 'gtk3-engine*' 'firefox' 'gftp-gtk' 'childsplay' 'billard-gl' 'chromium-bsu' 'scummvm' 'spring' 'dreamchess' 'warzone2100' 'xboard' 'scorched3d' 'enigma' 'gnome-games' 'armagetronad' 'pax-britannica' 'bastet' 'ninvaders' 'pacman4console' 'nsnake' 'greed' 'bsdgames' 'moon-buggy' 'steam' );
declare -a ALLGAMES=( 'game*' );
declare -a UETHEMES=( '2.0' '2.1' '2.2' '2.3' '2.4' '2.5' '2.6' '2.7' '2.8' '2.9' '3.0' '3.1' '3.2' '3.3' '3.4' '3.5' '3.6' '3.7' '3.8' '3.9' '4.0' '4.1' '4.2' '4.3' '4.4' '4.5' '4.6' '4.7' '4.8' '4.9' '5.0' '5.1' '5.2' '5.3' '5.4' '5.5' '5.6' '5.7' '5.8' '5.9' '6.0' '6.1' '6.2' '6.3' '6.5' '6.6' '6.7' '6.8' '6.9' );
declare -a EXTRADE=( "XFCE" "MATE" "KDE" "TRINITY" "LXDE" "AWESOME" "GNOME" "LXQT" "UNITY" "CINNAMON" "BUDGIE" "ENLIGHTENMENT" "PANTHEON" "DEEPIN" );
declare -a DEADD=( "xubuntu-desktop" "mate-desktop-environment" "kubuntu-full" "lubuntu-desktop" "awesome" "ubuntu-gnome-desktop" "lxqt" "ubuntu-desktop" "cinnamon" "ubuntu-budgie-desktop" "e17" "elementary-desktop" "ubuntudde-dde" );
# A work in progress ...
declare -a EXTRAPACKAGES=( "chkrootkit" "command-not-found" "viewnior" "bash-completion" "mate-system-monitor" "caja" "pluma" "engrampa" "caja-actions" "caja-admin" "caja-eiciel" "caja-extensions-common" "caja-gtkhash" "caja-image-converter" "caja-open-terminal" "caja-rename" "caja-seahorse" "caja-sendto" "caja-share" "caja-wallpaper" "caja-xattr-tags" "terminator" "filezilla" "gftp" "gdebi" "unrar" "clementine" "terminator" "pithos" );
declare -a DEVELOPMENTPACKAGES=( "chkrootkit" "alien" "command-not-found" "viewnior" "isomaster" 'alien' 'qtcreator' 'qt5-doc' 'qt5-doc-html qtbase5-doc-html' 'qtbase5-examples' 'qtdesigner' 'qtcreator' 'bluefish' 'boot-repair' 'tidy' 'nvme-cli' 'grub-customizer' 'ubuntu-dev-tools' 'nano' 'dialog' 'build-essential' 'git' 'subversion' 'cmake' 'vim' 'codelite' 'codeblocks' 'codeblocks-contrib' 'geany' 'kate' 'qt5-designer' 'qt5-make' 'qt4-designer' 'qt4-qmake' 'devscripts' 'dh-buildinfo' 'codium' 'gambas2' 'gambas3' 'qt5-default' 'qttools5-dev-tools' 'golang-go' );
# Removed 'android-sdk' 'brackets'
# End work in progress...
declare -a BASEPACKAGES=( 'nvme-cli' 'lsb-base' 'lsb-release' 'apt-utils' 'nano' 'build-essential' 'wget' 'bc' 'iputils-ping' 'nano' 'bash-completion' );

declare -a ICONS=( 'ultimate-edition-cursors-0.0.7_all.deb' 'ultimate-edition-female-themes-1.0-all.deb' 'ultimate-edition-icons-baby-blue-0.0.1_all.deb' 'ultimate-edition-icons-dark-glass.0.0.5_all.deb' 'ultimate-edition-icons-dark-glow.0.0.2_all.deb' 'ultimate-edition-icons-dark-one-0.0.1_all.deb' 'ultimate-edition-icons-gold-0.0.1_all.deb' 'ultimate-edition-icons-light-0.0.1_all.deb' 'ultimate-edition-icons-red-0.0.1_all.deb' 'ultimate-edition-sound-scheme-0.0.6_all.deb' );

declare -a ICONNAMES=( 'ultimate-edition-cursors' 'ultimate-edition-female-themes-1.0' 'ultimate-edition-icons-baby-blue' 'ultimate-edition-icons-dark-glass' 'ultimate-edition-icons-dark-glow' 'ultimate-edition-icons-dark-one' 'ultimate-edition-icons-gold' 'ultimate-edition-icons-light' 'ultimate-edition-icons-red' 'ultimate-edition-sound-scheme' );

declare -a FFPREFS=( '7qdy7sjf.default' 'q2l51o82.default' )
ROOTFOLDER="http://os-builder.com/UETOYS"
#apt-get install rocksndiamonds glob2 crack-attack xmoto frozen-bubble lincity bomberclone powermanga chromium-bsu lbreakout2 freecol
declare -a SMALLGAMES=( 'rocksndiamonds' 'glob2' 'pysol' 'xmoto' 'pysol' 'lincity' 'bomberclone' 'powermanga' 'chromium' 'chromium-bsu' 'pychess' 'lbreakout2' 'freecol' )

MinimalOS () {
	Encapsulate "Currently Un-implemented."
}

Chrome () {
    if [[ -d "/tmp/" ]]; then
        Encapsulate "Installing google chrome."
        cd /tmp/ || exit 1;
        wget "https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb"
        if [[ -s "google-chrome-stable_current_amd64.deb" ]]; then
            dpkg -i "google-chrome-stable_current_amd64.deb"
        fi
    else
        Error "No /tmp folder."
    fi
}
# Pulls stored cache if any, from the chroot environment to the .cache/ folder.
PullCache () {
	if [[ "${DEBUG}" ]]; then
		echo "DEBUGGING: we are in ${PWD} in function PullCache."
	fi
	if [[ "${CACHEOPTION}" == "none" ]]; then
		Encapsulate "Cacheoption specified as none, not doing any cacheing."
		return 0;
	fi
	BASEPULL="${1}"
	ARCH="${2}"
	if ! [[ "${BASEPULL}" && "${ARCH}" ]]; then
		Error "CRITICAL ERROR Pull Cache: Invalid caching switches provided. BASE: ${1} ARCH:${2}"
		exit 1;
	fi
	CACHESIZE=$(du -hs "edit/var/cache/apt/archives/" | awk '{print $1}')
	if [[ "${CACHESIZE}" == "4.0K" ]]; then
		CACHESIZE=""
	fi
	if [[ -d "${CACHINGFOLDER}/${BASEPULL}/${ARCH}/apt/" ]]; then
		if [[ "${CACHESIZE}" ]]; then
			Encapsulate "Pulling ${CACHESIZE} of cache for ${BASEPULL} ${ARCH} build. Please wait..."
			SUCCESS=$(cp edit/var/cache/apt/archives/*.deb "${CACHINGFOLDER}/${BASEPULL}/${ARCH}/apt/") 2>/dev/null
		fi
		if ! [[ "${SUCCESS}" ]]; then
			Encapsulate "Success"
			Encapsulate "Clearing Cache from build."
			SUCCESS=$(rm edit/var/cache/apt/archives/*.deb) 2>/dev/null
		else
			Encapsulate "Failure"
		fi
	else
		Encapsulate "No cache folder, first ${BASEPULL} ${ARCH} based O/S build?"
		mkdir -p "${CACHINGFOLDER}/${BASEPULL}/${ARCH}/apt/"
	fi
		#TMP CACHE

	CACHESIZE=""
	CACHESIZE=$(du -hs "edit/tmp/" | awk '{print $1}')
	if [[ "${CACHESIZE}" == "4.0K" ]]; then
		CACHESIZE=""
	fi
	CURRENTFOLDER="${PWD}"
	if [[ "${CACHESIZE}" ]]; then
		if [[ -d "${CACHINGFOLDERTEMP}" ]]; then
			Encapsulate "Initiating Temp cache sync operation of ${CACHESIZE}. Please wait"
			if [[ -d "edit/tmp/" ]]; then
				cd "edit/tmp/" || exit 1;
				shopt -s dotglob
				shopt -s nullglob
				array=(*/)
				for dir in "${array[@]}"; do Encapsulate "Removing temp dir: $dir"; rm -R "$dir" 2>/dev/null; done
				shopt -s extglob
				SUCCESS=$(cp !(*-core-files.deb) "${CACHINGFOLDERTEMP}/") 2>/dev/null
				shopt -u extglob
				shopt -u dotglob
				shopt -u nullglob
				cd "${CURRENTFOLDER}" || exit 1;
			fi

			if ! [[ "${SUCCESS}" ]]; then
				Encapsulate "Success"
			else
				Encapsulate "Failure"
			fi
		else
			Encapsulate "No Temp cache folder, first build?"
			mkdir -p "${CACHINGFOLDERTEMP}"
		fi
	else
		Encapsulate "No Temp cache folder, first build?"
		mkdir -p "${CACHINGFOLDERTEMP}"
	fi
	sync
}

DisableIPV6 () {
	Center "Disabling IPV6 Protocol."
	sysctl -w net.ipv6.conf.all.disable_ipv6=1
	sysctl -w net.ipv6.conf.default.disable_ipv6=1
	sysctl -w net.ipv6.conf.lo.disable_ipv6=1
	Encapsulate "Refreshing sysctl"
	sysctl --system
}

EnableIPV6 () {
	Center "Enabling IPV6 Protocol."
	sysctl -w net.ipv6.conf.all.disable_ipv6=0
	sysctl -w net.ipv6.conf.default.disable_ipv6=0
	sysctl -w net.ipv6.conf.lo.disable_ipv6=0
	Encapsulate "Refreshing sysctl"
	sysctl --system
}

# Set a timer to display duration of download (s)
# Usage:  Timer [start|stop]
DownloadTimer () {
   	Tcmd="${1^^}"

    case "$Tcmd" in
        START) _StartSecs=$(date +%s)
            ;;
        STOP) _StopSecs=$(date +%s)
                [[ ! $_StartSecs ]] && Error "[Internal Error] Timer did not record a start time." && return
                ((_DiffSecs=_StopSecs-_StartSecs))
                DLAPSE=$(date -u -d@"$_DiffSecs" +"%-Hh%-Mm%-Ss")
            ;;
        *) Error "[Internal Error] Unknown arg ${Tcmd}"
            ;;
    esac
	TOTALTIME+="$_DiffSecs"
}

# Download various packages showing progression...
Download () {
    local url="${1}"
	FILENAME=$(echo "${url##*/}")
	if [[ -f "${FILENAME}" ]]; then
		Encapsulate "${FILENAME} exists, deleting for re-download."
		rm "${FILENAME}"
	fi
    Encapsulate "Downloading: ${1}"
	Encapsulate "Filename: ${FILENAME}"
	DownloadTimer "Start"
    wget --progress=dot $url 2>&1 | grep --line-buffered "%" | sed -u -e "s,\.,,g" | awk '{printf("%4s", $2)}'

    echo -ne ""
	DownloadTimer "Stop"
	FileSize "${FILENAME}"
	#echo $?
    Encapsulate "Download complete: ${FILENAME} ${FORMATTED} bytes (${TRUESIZE}). Download time: ${DLAPSE}"
}

Finish () {
    FullBar
	Encapsulate "Here, the world is yours.  Enjoy, TheeMahn"
	FullBar
	UNHOLD=$(apt-mark unhold fonts-noto* snapd mate-user-guide fluid-soundfont-gm calibre)
	apt-get clean
	apt-get autoclean
	Encapsulate "Unmounting points..."
	umount /dev/pts >/dev/null 2>&1
	umount /proc >/dev/null 2>&1
	umount /sys >/dev/null 2>&1
	FullBar
}

trap Ctrl_c INT
trap Finish EXIT

HOLD=$(apt-mark hold fonts-noto* snapd mate-user-guide fluid-soundfont-gm calibre)
#Work in progress...
InstallIcons () {
	for EACH in "${ICONS[@]}"
	do
		FTG="${ROOTFOLDER}/${EACH}"
		for INSTALLNAME in "${ICONNAMES[@]}"
		do
			Encapsulate "Checking installation of ${INSTALLNAME}:"
			INSTALLED=$(dpkg-query -l "${INSTALLNAME}" 2>/dev/null | grep "ii" 2>/dev/null)
			if ! [[ "${INSTALLED}" ]]; then
				Encapsulate "Not installed."
				Encapsulate "Checking cache for: ${EACH}"
				if ! [[ -f "${EACH}" ]]; then
					Encapsulate "Does not exist. Downloading ${EACH}:"
					Download "${FTG}"
					if [[ -s "${EACH}" ]]; then
						Encapsulate "Installing ${EACH}:"
						INSTALL=$(dpkg -i "${EACH}" 2>/dev/null)
						if [[ "${INSTALL}" ]]; then
							Encapsulate "Done."
						else
							Error "Failed."
						fi
					else
						Error "Failed to download ${FTG}"
						Error "Please report issue to TheeMahn <theemahn@os-builder.com>."
					fi
				else
					INSTALL=$(dpkg -i "${EACH}" 2>/dev/null)
					if [[ "${INSTALL}" ]]; then
						Encapsulate "Installing ${EACH} from cache: Done"
					else
						Error "Installing ${EACH} from cache: Failed."
					fi
				fi
				if [[ -f "cache" ]]; then
					rm "${EACH}"
				fi
			else
				Encapsulate "Ultimate edition ${EACH} theme has been installed."
			fi
			array_counter=$((array_counter + 1))
		done
	done
	FullBar
}

Timer "Start" "${APPNAME}"
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

IsMounted () {
	MPOINTS=();
	declare -i INDEX;
	declare -i MOUNTED;
	OIFS=$IFS
	IFS=$'\n'
	MPOINTS=($(mount))
	IFS=$OIFS
	for EACH in "${MPOINTS[@]}"
	do
		MOUNTED=$(echo "${EACH}" | grep "${1}" | wc -l)
		if [[ "${MOUNTED}" -ge 1 ]]; then
			Encapsulate "#${INDEX}: ${EACH} is mounted."
			return "#${INDEX}: ${EACH} is mounted."
		else
			return 0
		fi
		INDEX=$((INDEX + 1))
	done
}

# LTS Detection
if [[ -f "/etc/lsb-release" ]]; then
	ISLTS=$(grep -i "LTS" /etc/lsb-release)
	if [[ "${ISLTS}" ]]; then
		LTS="YES"
	else
	    LTS="NO"
	fi
fi

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
}

UpdateGrub () {
	GRUBB=$(type -p update-grub)
	if [[ "${GRUBB}" ]]; then
		Encapsulate "Updating Grub..."
		update-grub 2>/dev/null
		Encapsulate "Updating initramfs..."
		update-initramfs -u -k all >/dev/null 2>&1
		Encapsulate "UnMounting points."
		umount /dev/pts >/dev/null 2>&1
		umount /proc >/dev/null 2>&1
		umount /sys >/dev/null 2>&1
        FullBar
	fi
}

MountPoints () {
	CheckRoot "$@"
	if [[ -f "/dev/null" ]]; then
		Error "Repairing /dev/null issue."
		SUPPRESS=$(rm -f /dev/null; mknod -m 666 /dev/null c 1 3)
	fi
	export HOME=/root
	export LC_ALL=C
	Encapsulate "Mounting necessary point(s)."
	declare -a MOUNTPOINTS;
	declare -a MOUNTTYPES;
	MOUNTTYPES=(); # RESET ARRAY if acclible
	MOUNTPOINTS=( "/dev/pts" "/proc" "/sys" )
	MOUNTTYPES=( "devpts" "proc" "sysfs" )
	declare -i INDEX;
	for EACH in "${MOUNTPOINTS[@]}"
	do
		# mount -t devpts none /dev/pts
		MTYPE="${MOUNTTYPES[$INDEX]}"
		IsMounted "${MTYPE}"
		if [[ "$?" ]]; then
			Encapsulate "Mounting: ${EACH} Type: ${MTYPE}"
			sudo mount -t "${MTYPE}" none "${EACH}" >/dev/null 2>&1
		else
			Encapsulate "Mount: ${EACH} Type: ${MTYPE} is already mounted."
		fi
		(( INDEX ++ ))
	done
	Center "Refreshing sources"
	apt-get update & Spinner "Running apt-get update..."
}

Compiz () {
	COMPIZ="/etc/xdg/autostart/compiz.desktop"
	VersionDump
	Center "Refreshing sources"
	apt-get update & Spinner "Running apt-get update..."
	Encapsulate "Installing Compiz"
	apt-get install -f -y compiz compiz-plugin*
	if [[ -f /usr/bin/compiz ]]; then
		Center "Creating startup application: Compiz"
		echo "[Desktop Entry]" > "$COMPIZ"
		echo "Name=Compiz" >> "$COMPIZ"
		echo "Name[en_GB]=Compiz" >> "$COMPIZ"
		echo "Type=Application" >> "$COMPIZ"
		echo "Exec=/usr/bin/compiz --replace" >> "$COMPIZ"
		echo "Terminal=false" >> "$COMPIZ"
		echo "Icon=gnome-do" >> "$COMPIZ"
		echo "Comment=Engages Compiz on startup" >> "$COMPIZ"
		echo "Categories=System;" >> "$COMPIZ"
	else
		Error "Compiz is not installed at /usr/bin/compiz"
		exit 1;
	fi
	Encapsulate "Done."
	FullBar
}

FireFox () {
    if [[ -f "/etc/lsb-release" ]]; then
        CODENAME=$(grep -i "codename" /etc/lsb-release | cut -d "=" -f2)
		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"
        fi
		MSERVER=$(grep -i "minimal" /etc/lsb-release)
		if [[ "${MSERVER}" ]]; then
            DISTTYPE="Minimal Server"
        fi
		DEVELOPER=$(grep -i "developer" /etc/lsb-release)
		if [[ "${DEVELOPER}" ]]; then
            DISTTYPE="Developer"
        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
}

CustomGrub () {
    case "${ARCH}" in
	    armhf)KERNELPACKAGES="linux-generic-lts-trusty";GRUBPACKAGES="grub-legacy-ec2";;
	    amd64)KERNELPACKAGES="linux-generic casper lupin-casper";GRUBPACKAGES="grub";;
	    i386)KERNELPACKAGES="linux-generic casper lupin-casper";GRUBPACKAGES="grub";;
	    powerpc)KERNELPACKAGES="linux-image-powerpc-smp casper lupin-casper";GRUBPACKAGES="grub2-common";;
	    *)KERNELPACKAGES="linux-generic linux-image-generic linux-headers-generic casper lupin-casper";GRUBPACKAGES="grub";;
    esac
	if ! [[ "${ARCH}" == "armhf" ]]; then
		INSTALLED=$(dpkg-query -l "${GRUBPACKAGE}S" | grep 'ii' 2>/dev/null)
		if [[ -f "/etc/default/grub" || "${INSTALLED}" ]]; then
			PRECUSTOM=$(grep -i "ultimate" /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
					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="/usr/share/wallpapers/Ultimate_Edition_'${DISTREL}'.png"' >> /etc/default/grub
					echo 'export GRUB_MENU_PICTURE="/usr/share/wallpapers/Ultimate_Edition_'${DISTREL}'.png"' >> /etc/default/grub
					echo 'export GRUB_COLOR_NORMAL="black/black"' >> /etc/default/grub
					echo 'export GRUB_COLOR_HIGHLIGHT="red/black"' >> /etc/default/grub
					echo 'GRUB_FONT="/boot/grub/liberation.pf2"' >> /etc/default/grub
				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."
		fi
	else
		Encapsulate "No Grub customization for arm based products currently supported."
	fi
	# grub2-theme-ultimate-edition-6.3_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 "${PREREQ}" 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
			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 "${PREREQ}" network-manager network-manager-gnome 2>/dev/null
		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
			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 network-manager network-manager-gnome 2>/dev/null
		fi
	fi
}

GrubSession () {
	FullBar
	declare -a ENTRIES=();
	declare -i INDEX;
	declare -i RAM_SESSION;
	INDEX=0
	RAM_SESSION=0
	if [[ -f "/ram_session" ]]; then
		Encapsulate "Ram Session found."
		RAM_SESSION=1
		if [[ -f "/etc/default/grub" ]]; then
			GREPIT=$(grep "GRUB_DEFAULT=" "/etc/default/grub")
			case "${GREPIT}" in
				saved) Center "Grub Default is currently saved to the last.";;
				*) Center "Grub Default is currently set to: ${GREPIT}";;
			esac
			OIFS=$IFS
			IFS=$'\n'
			ENTRIES=($(awk -F\' '/menuentry / {print $2}' "/boot/grub/grub.cfg"))
			IFS=$OIFS
			for EACH in "${ENTRIES[@]}"
			do
				Encapsulate "${INDEX}. ${EACH}"
				INDEX=$((INDEX + 1))
			done
			FullBar
			if [ -e "/original_os" ]; then
				if ! [[ "${RAMSESSION}" ]]; then
					read -p "Default session? [#]: " ANSWER
					if ! [[ "${ANSWER}" == "${GREPIT}" ]]; then
						FullBar
						Encapsulate "Updating default grub entry to ${ENTRIES[${ANSWER}]}"
						sudo sed -i "s/GRUB_DEFAULT=.*/GRUB_DEFAULT=${ANSWER}/g" "/etc/default/grub"
					fi
				fi
			fi
		else
			Error "Default grub not found, exiting."
			exit 1;
		fi
		#elif [[ -f "/original_os" && ! "${RAMSESSION}" ]]; then
		#Encapsulate "Original O/S found."
		#Encapsulate "Disabling ${PROGNAME} shutdown service."
	fi
	UpdateGrub "$@"
}

Repositories () {
	DISTREL=$(cat /etc/lsb-release | sed -n 's/^DISTRIB_RELEASE=[ \t]*\(.*\)/\1/p' 2>/dev/null)
	INSTALLED=$(dpkg-query -l "ultimate-edition-repositories" | grep "ii" 2>/dev/null)
	if ! [[ "${INSTALLED}" ]]; then
		Center "Retriving Ultimate Edition Repositories..."
		FullBar
		if ! [[ -f "ultimate-edition-repositories-0.2.2-apt-source_all.deb" ]]; then
			wget "${ROOTFOLDER}/ultimate-edition-repositories-0.2.2-apt-source_all.deb"
		fi
		if [[ -f "ultimate-edition-repositories-0.2.2-apt-source_all.deb" ]]; then
			dpkg -i "ultimate-edition-repositories-0.2.2-apt-source_all.deb"
			if [[ -f "cache" ]]; then
				rm "ultimate-edition-repositories-0.2.2-apt-source_all.deb"
			fi
		fi
	else
		Center "Ultimate Edition Repositories already installed."
	fi

	INSTALLED=$(dpkg-query -l "ultimate-edition-keysnatcher" | grep "ii" 2>/dev/null)
	KEYSNATCHER="ultimate-edition-keysnatcher-1.1.2_all.deb"
	if ! [[ "${INSTALLED}" ]]; then
		# Future builds will be SPECIFIC via ${DISTREL} value
		# wget http://ultimateedition.info/Ultimate_Edition_${DISTREL}/ultimate-edition-keysnatcher-1.0.0_all.deb
		if ! [[ -f "${KEYSNATCHER}" ]]; then
			echo -n "Downloading ${KEYSNATCHER}:"
			Download "${ROOTFOLDER}/${KEYSNATCHER}"
		fi
		if [[ -s "${KEYSNATCHER}" ]]; then
			dpkg -i "${KEYSNATCHER}"
			if [[ -f "cache" ]]; then
				rm "${KEYSNATCHER}"
			fi
		else
			Error "File not found: ${KEYSNATCHER}"
		fi
	else
		Center "Ultimate Edition Keysnatcher previously installed."
	fi
	Encapsulate "Pulling dependancies, please wait."
	apt-get install -f -y
	if [[ -f "ubiquity-slideshow-ubuntu_999_all.deb" ]]; then
		Encapsulate "Installing: ubiquity-slideshow-ubuntu_999_all.deb"
		dpkg -i "ubiquity-slideshow-ubuntu_999_all.deb" 2>/dev/null
	else
		Encapsulate "ubiquity-slideshow-ubuntu_999_all.deb not found, KDE?"
	fi
	if [[ -f "ubiquity-slideshow-kubuntu_999_all.deb" ]]; then
		Encapsulate "Installing: ubiquity-slideshow-kubuntu_999_all.deb"
		dpkg -i "ubiquity-slideshow-kubuntu_999_all.deb"
	else
		Encapsulate "ubiquity-slideshow-kubuntu_999_all.deb not found, Gnome / Mate?"
	fi
	INSTALLED=$(dpkg-query -l "dbus" | grep "ii" 2>/dev/null)
	if ! [[ "${INSTALLED}" ]]; then
		Center "Installing dbus..."
		apt-get install -f -y dbus
	else
		Center "Dbus previously installed."
	fi
	EXISTS=$(type -p keysnatcher)

	if [[ -f "/etc/lsb-release" ]]; then
		Center "Distro release info:"
		FullBar
		lsb_release -a
		FullBar
		if [[ -f "/etc/lsb-release" ]]; then
    		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"
            fi
			MSERVER=$(grep -i "minimal" /etc/lsb-release)
			if [[ "${MSERVER}" ]]; then
                DISTTYPE="Minimal Server"
            fi
		fi
		if [[ "${MSERVER}" ]]; then
			SERVER=""
		fi
    	ULTIMATEEDITION=$(grep -i "ultimate" /etc/lsb-release)
        #Center "DEBUGGING: ULTIMATEEDITION: $ULTIMATEEDITION GAMERS:$GAMERS LITE:$LITE"
	else
		Error "ERROR: Massive failure, no dist-release info, exiting."
		EXIT
	fi
	Encapulate "Updating sources."
	apt-get update & Spinner "Running apt-get update..."
	Encapsulate "Rectifying inital dependancies"
	apt-get install -f -y --allow-unauthenticated
	if ! [[ -f "${HOME}/.keysnatcher" ]]; then
		if [[ "${EXISTS}" ]]; then
			keysnatcher --snatch
			keysnatcher --fixerrors
		fi
	fi
}

DistUpgrade () {
	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 & Spinner "Running apt-get update..."
	Encapsulate "Forcing packages if any."
	apt-get install -f -y 2>/dev/null

	Encapsulate "Distribution upgrading, please wait..."
	apt-get dist-upgrade & Spinner "Running apt-get dist upgrade..."
    INSTALLED=$(dpkg -l | grep "linux-generic")
    if ! [[ "${INSTALLED}" ]]; then
        Encapsulate "Installing minimal to boot."
        apt-get install -f -y linux-generic casper lupin-casper fonts-liberation fonts-liberation2 bcmwl-kernel-source grub2
    else
        Encapsulate "Kernel already installed."
    fi
	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
#declare -a ENTIREPACKAGES=();
#let i=0

#while read -r line ; do
#    arr=(${line})
#    let i=i+1
#    _constr+="${arr[2]} "
#done < <(dpkg -l | grep "4.15.0-9" | grep -v "libc" | awk '{print ${2}}')

#echo "${i}"
#echo "${_constr}"

#                ENTIREPACKAGES=$(dpkg -l | grep "${KERNEL}" | grep -v "libc" | awk '{print ${2}}')
#                IFS=$'\n'
#                if [[ "${DEBUG}" ]]; then
#                    echo "DEBUGGING ENTIREPACKAGES: ${ENTIREPACKAGES[1]}"
#                fi
#                for PACKAGE in "${ENTIREPACKAGES[@]}"
#    			 do
#                    Encapsulate "Processing package: ${PACKAGE}"
#					INSTALLED=$(dpkg -l "${PACKAGE}" | grep -i 'ii')
#					if [[ "${INSTALLED}" ]];then
#						Encapsulate "${PACKAGE} is installed and will be removed, because we already have a predominant kernel."
#						BUILDUNINSTALL+=" ${PACKAGE}"
#					fi
#				done
#				Encapsulate "THIS IS ALL YOU CARE ABOUT: $BUILDUNINSTALL"
#				Encapsulate "Purging: $BUILDUNINSTALL"
#                Encapsulate "Prompting at this stage of development:"
#                #dpkg -l | grep "${KERNEL}" | cut -d ' ' -f3 | xargs -p sudo apt-get -y purge
				# allow end user to make the decision for now.
				#apt-get purge $(dpkg --list |egrep 'linux-image-[0-9]' |awk '{print ${3},${2}}' |sort -nr |tail -n +2 |grep -v $(uname -r) |awk '{ print ${2}}')
				#apt-get remove --purge "$BUILDUNINSTALL"
				#UpdateGrub
#			fi
#            INDEX=$((INDEX+1))
#		done
#	else
#		Encapsulate "Congradulations only one kernel detected: ${KERNELS[*]}."
#		UpdateGrub
#		FullBar
#	fi
}

UltimateApps () {
	for i in "${INSTALLNAMES[@]}"
	do
		INSTALLED=$(dpkg-query -l "${i}" 2>/dev/null | grep "ii" 2>/dev/null)
		if ! [[ "${INSTALLED}" ]]; then
			Encapsulate "Checking installation of ${i}: Not Installed."
			FTG="${FILELIST[$array_counter]}"
			if ! [[ -f "${FTG}" ]]; then
				Encapsulate "Checking cache for ${FTG}: Does not exist."
				Encapsulate "Downloading ${i}:"
				Download "${ROOTFOLDER}/${FTG}"
				if [[ -s "${FTG}" ]]; then
					INSTALL=$(dpkg -i "${FTG}" 2>/dev/null)
					if [[ "${INSTALL}" ]]; then
						Encapsulate "Installing ${i}: Installed."
					else
						Error "Installing ${i}: Failed."
					fi
				else
					Error "Failed to download ${i}."
				fi
			else
				Encapsulate "Checking cache for ${FTG}: Exists."
				Encapsulate "Installing ${i}:"
				INSTALL=$(dpkg -i "${FTG}" 2>/dev/null)
				if [[ "${INSTALL}" ]]; then
					Encapsulate "${i} has been installed successfully."
				else
					Error "Failed to install ${i}."
				fi
			fi

			if [[ -f "cache" ]]; then
				rm "${FTG}"
			fi
		else
			Encapsulate "${i} has already been Installed."
		fi
		array_counter=$((array_counter + 1))
	done
}

#Smash spyware, we want our users free to do as they like w/o being spied on...
AntiMalware () {
	# 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 "$@"
#DETECT CHROOTED ARCH
ARCHITECTURE=0
TESTIT=$(getconf LONG_BIT)
if [ "${TESTIT}" = "64" ]; then
	ARCH="amd64"
	ARCHITECTURE=1
else
	ARCH="i386"
	ARCHITECTURE=1
fi
ARM=$(uname -a | grep "arm")
PPC=$(uname -a | grep "ppc")
if [[ "${PPC}" && "${ARCHITECTURE}" -lt 1 ]]; then
	ARCH="powerpc"
	Center "Powerpc based release detected."
	ARCHITECTURE=1
else
	Center "Architecture detected as ${ARCH}. Not scanning for powerpc."
fi
if [[ "$ARM" && "${ARCHITECTURE}" -lt 1 ]]; then
	Center "ARMHF based release detected."
	ARCH="armhf"
	ARCHITECTURE=1
else
	Center "Architecture detected as ${ARCH}. Not scanning for arm support."
fi

root_inode=$(stat -c %i /);
FULLRIGHTS=$(echo "$*" | grep -i "fullrights")
if [ "$root_inode" -ne 2 ]; then
	Encapsulate "Chroot environment detected. Setting up appropriately for ${ARCH}"
else
	if ! [[ "${FULLRIGHTS}" ]]; then
		Encapsulate "Non-chroot environment detected. I refuse to execute. Exiting..."
		exit 1;
	fi
fi


if [[ -d "/tmp" ]]; then
	cd "/tmp/" || exit 1
fi
MountPoints "$@"
sync
ISMOUNTED=$(mount | grep -i "pts" >/dev/null 2>&1)
if [[ "${ISMOUNTED}" ]]; then
	Encapsulate "/dev/pts point mounted."
else
	Encapsulate "Mounting necessary /dev/pts point."
	mount -t devpts none /dev/pts >/dev/null 2>&1
fi
ISMOUNTED=$(mount | grep -i "proc") >/dev/null 2>&1
if [[ "${ISMOUNTED}" ]];then
	Encapsulate "Proc point mounted."
else
	Encapsulate "Mounting necessary proc point."
	mount -t proc none /proc >/dev/null 2>&1
fi
ISMOUNTED=$(mount | grep -i "sysfs") >/dev/null 2>&1
if [[ "${ISMOUNTED}" ]];then
	Encapsulate "Sysfs point mounted."
else
	Encapsulate "Mounting necessary sysfs point."
	mount -t sysfs none /sys >/dev/null 2>&1
fi
export HOME=/root
export LC_ALL=C
cd "/tmp/" || exit 1
if [[ "${FULLRIGHTS}" ]]; then
	Encapsulate "Fullrights switch engaged.  Mounting all necessary points."
	mount -t devpts none /dev/pts 2>/dev/null
	mount -t proc none /proc 2>/dev/null
	mount -t sysfs none /sys 2>/dev/null
fi
FullBar

Themes () {
#if [[ "${DEBUG}" ]]; then
#    Encapsulate "DEBBUGGING: @:$@ 1:${1} 2:${2} 3:${3}"
#fi
	INFOLDER="${PWD}"
	if ! [[ "${2}" == "" ]]; then
		Center "Installing Ultimate Edition Theme for ${2} as requested."
    	if [[ -d /tmp/ ]]; then
    	    cd "/tmp/" || exit 1;
    	    Encapsulate "Downloading ultimate-edition-theme-${2}_all.deb, please wait."
    	    Download "${THEMEFOLDER}/ultimate-edition-theme-${2}_all.deb"
    	    if [[ -s "ultimate-edition-theme-${2}_all.deb" ]]; then
    	        Encapsulate "Installing ultimate-edition-theme-${2}_all.deb."
    	        FullBar
    	        INSTALL=$(dpkg -i "ultimate-edition-theme-${2}_all.deb" 2>/dev/null)
    	        INSTALLED=$(dpkg-query -l "ultimate-edition-theme-${2}" 2>/dev/null | grep "ii" 2>/dev/null)
    	        if [[ "${INSTALLED}" ]]; then
    	            Encapsulate "ultimate-edition-theme-${2} installed successfully."
    	            Encapsulate "Cleaning up."
    	            if [[ -f "ultimate-edition-theme-${2}_all.deb" ]]; then
    	                rm "ultimate-edition-theme-${2}_all.deb"
    	            fi
				else
    	    		Error "Error: Installing ultimate-edition-theme-${2}."
    	    		FullBar
    	    		exit 1;
				fi
			fi
		else
    	   	Error "No /tmp/ directory found."
    	   	FullBar
    	   	exit 1;
    	fi
		FullBar
		Center "Installing Plymouth theme for ${2}"
    	apt-get install -f -y --allow-unauthenticated plymouth-label
    	TESTEXIST=$(dpkg -l | grep -i "plymouth-theme-kubuntu*")
    	if [[ "$TESTEXIST" ]]; then
    	    Encapsulate "Purging Kubuntu plymouth theme."
    	    apt-get remove --purge --yes --assume-yes plymouth-theme-kubuntu*
    	    #apt-get remove --purge plymouth-themes
    	fi
		# ultimate-edition-4.4-plymouth_all.deb
 		INSTALLED=$(dpkg-query -l "ultimate-edition-plymouth-${2}" | grep "ii")
    	DISTREL="${2}"
    	if ! [[ "${INSTALLED}" ]]; then
			if ! [[ -f "ultimate-edition-plymouth-${DISTREL}_all.deb" ]]; then
			    Encapsulate "Retrieving plymouth splash for Ultimate Edition ${DISTREL}:"
    	        Download "${THEMEFOLDER}/ultimate-edition-plymouth-${2}_all.deb"
		        if [[ -f "ultimate-edition-plymouth-${DISTREL}_all.deb" ]]; then
    		        Encapsulate "Installing ultimate-edition-plymouth-${DISTREL}_all.deb:"
    	            INSTALL=$(dpkg -i "ultimate-edition-plymouth-${DISTREL}_all.deb" 2>/dev/null)
    	            if [[ "${INSTALL}" ]]; then
    	                Encapsulate "Installed."
    	            else
    		            Error "Failed."
    	            fi
    			else
    	          	Encapsulate "Installing ultimate-edition-plymouth-${DISTREL}_all.deb from cache:"
    	           	INSTALL=$(dpkg -i "ultimate-edition-plymouth-${DISTREL}_all.deb" 2>/dev/null)
    	            if [[ "${INSTALL}" ]]; then
    	          	    Encapsulate "Installed."
    	            else
    	           	    Error "Failed."
    	                exit 1;
    	            fi
    	        fi
    	        if [[ -f "ultimate-edition-plymouth-${DISTREL}_all.deb" ]]; then
    	           	rm "ultimate-edition-plymouth-${DISTREL}_all.deb"
    	        fi
			fi
		else
			Center "Ultimate Edition ${DISTREL} Plymouth already installed."
    	fi
		FullBar
		GENPACKAGE="${THEMEFOLDER}/ultimate-edition-grub-${DISTREL}_all.deb"
		VALID=$(ValidateURL "${GENPACKAGE}")
		Encapsulate "Downloading: ${GENPACKAGE}"
		Download "${GENPACKAGE}"
		if [[ -f "ultimate-edition-grub-${DISTREL}_all.deb" ]]; then
			Encapsulate "Installing: ultimate-edition-grub-${DISTREL}_all.deb"
			FullBar
			dpkg -i "ultimate-edition-grub-${DISTREL}_all.deb"
			FullBar
			Encapsulate "Cleaning up."
			rm  "ultimate-edition-grub-${DISTREL}_all.deb"
			#UpdateGrub
			exit 0;
		else
			Error "ultimate-edition-grub-${DISTREL}_all.deb does not exist, TheeMahn Made it yet?"
			exit 1;
		fi
	fi
	Center "Installing Ultimate Edition Themes..."
	FullBar
	for i in "${UETHEMES[@]}"
	do
		ZZ="ultimate-edition-theme-${i}"
		# ultimate-edition-theme-4.4-all.deb
		DEBFILE="ultimate-edition-theme-${i}_all.deb"
		Encapsulate "Checking installation of ${ZZ}:"
		INSTALLED=$(dpkg-query -l "${ZZ}" 2>/dev/null | grep "ii" 2>/dev/null)
		if ! [[ "${INSTALLED}" ]]; then
			Encapsulate "Not installed."
			Encapsulate "Checking cache for: ${ZZ}"
			FTG="$DEBFILE"
			if ! [[ -f "${FTG}" ]]; then
				Encapsulate "Does not exist. Downloading ${ZZ}:"
				Download "${THEMEFOLDER}/${FTG}"
				if [[ -s "${FTG}" ]]; then
					Encapsulate "Installing ${ZZ}:"
					INSTALL=$(dpkg -i "${FTG}" 2>/dev/null)
					if [[ "${INSTALL}" ]]; then
						Encapsulate "Done."
					else
						Error "Failed."
					fi
				else
					Error "Failed to download ${ZZ}"
					Error "Please report issue to TheeMahn <theemahn@os-builder.com>."
				fi
			else
				INSTALL=$(dpkg -i "${FTG}" 2>/dev/null)
				if [[ "${INSTALL}" ]]; then
					Encapsulate "Installing ${i} from cache: Done"
				else
					Error "Installing ${i} from cache: Failed."
				fi
			fi
			if [[ -f "cache" ]]; then
				rm "${FTG}"
			fi
		else
				Encapsulate "Ultimate edition ${i} theme has been installed."
		fi
		array_counter=$((array_counter + 1))
	done
	FullBar
	InstallIcons
	apt-get install -y -f
	GENPACKAGE="${THEMEFOLDER}/ultimate-edition-grub-${DISTREL}"
	GENPACKAGE+="_all.deb"
	VALID=$(ValidateURL "${GENPACKAGE}")
	Encapsulate "Downloading : ${GENPACKAGE}"
	GRUBPACKAGE="ultimate-edition-grub-${DISTREL}"
	GRUBPACKAGE+="_all.deb"
	Download "${GENPACKAGE}"
	dpkg -i "${GRUBPACKAGE}"
	FullBar
	FireFox "$@"
}

WineUp () {
    # fix it has failed. prior
    ISSUE=$(dpkg --add-architecture i386)
    # refresh sources
    Encapsulate "Refreshing sources"
    apt-get update & Spinner "Running apt-get update..."

    Encapsulate "LTS: $LTS"

    declare -a WINEVERSIONS=( 'wine-stable' 'winehq-stable' 'winehq-unstable' 'wine-unstable' 'wine-development' );
    declare -a STABLEWINE=( 'winehq-stable' 'wine-stable' );
    declare -a UNSTABLEWINE=( 'winehq-unstable' 'wine-unstable' 'wine-development' );

    # test installation first
    for EACH in "${WINEVERSIONS[@]}"
    do
        ISINSTALLED=$((dpkg-query -l "${EACH}" | grep "ii") 2>/dev/null)
        if [[ "${ISINSTALLED}" ]]; then
            INSTALLED=1
            break;
        fi
    done
    if [[ "${INSTALLED}" != "1" ]]; then
        if [[ "$LTS" == "YES" ]]; then
            for EACH in "${STABLEWINE[@]}"
            do
                ISAVAILIBLE=$(apt-cache search "${EACH}" 2>/dev/null)
                if [[ "${ISAVAILIBLE}" ]]; then
                    Encapsulate "Stable Wine version availible: ${EACH}"
                    TOINSTALL="${EACH}"
                fi
            done
        else
            for EACH in "${UNSTABLEWINE[@]}"
            do
                ISAVAILIBLE=$(apt-cache search "${EACH}" 2>/dev/null)
                if [[ "${ISAVAILIBLE}" ]]; then
                    Encapsulate "Unstable Wine version availible: ${EACH}"
                    TOINSTALL="${EACH}"
                fi
            done
        fi
    else
        Encapsulate "Wine has already been installed."
    fi
    if [[ "${INSTALLED}" != "1" ]]; then
        if [[ "${TOINSTALL}" ]]; then
            Encapsulate "Installing: ${TOINSTALL}"
            FullBar
            apt-get install -f -y "${TOINSTALL}"
        else
            Error "No wine version to install."
        fi
    fi
}

QuestForSpeed () {
    HOLD=$(apt-mark hold fonts-noto-* mate-user-guide mate-user-guide calibre)
    #HOLD=$(apt-mark hold snapd)
	declare -i INDEX
	INDEX=0
	# Setup an array to store all good packages.
	declare -a CLEANPACKAGES=();
	# Case the joint, what type of O/S is the user wanting to build.
	Center "Installing: ${DISTTYPE}, please wait this will most likely take a long time."
	Encapsulate "Add recommended packages: ${RECOMMENDS^^}"
	FullBar
	case "${DISTTYPE}" in
		basepackages) # Install Base Packages.
			Center "Installing base packages."
			# Test to see if we have broken packages.
			(apt-get install -y -f "${BASEPACKAGES[@]}" 2>errors)
			# Woopsie, Repo issue?  Let's rectify.
			if [[ -s "errors" ]]; then
				FullBar
				Encapsulate "Broken packages detected, Rectifying."
				# Build a array of good packages rip out the bad packages.
				# Break out a nested for loop.
				for EACH in "${BASEPACKAGES[@]}";
				do
					CHECKFORERROR=$(grep -i "${EACH}"  "errors")
					if ! [[ "${CHECKFORERROR}" ]]; then
						CLEANPACKAGES[${INDEX}]="${EACH}"
						INDEX=$((INDEX + 1))
					else
						Encapsulate "Package: ${EACH} is broken and will not be installed."
					fi
				done
				FullBar
				if [[ "${RECOMMENDS^^}" == "NO" ]]; then
					apt-get install -y -f --allow-unauthenticated --no-install-recommends "${CLEANPACKAGES[@]}"
				else
					apt-get install -y -f "${CLEANPACKAGES[@]}"
				fi
			else
				Center "All packages for ${DISTTYPE}, were successfully installed."
			fi
			Encapsulate "Installing Keysnatcher & Ultimate Edition repositories"
			Repositories "$@"
			FullBar;;
		developer) # Install development based packages.
			Center "Installing development based packages."
			# Test to see if we have broken packages.
			(apt-get install -y -f "${DEVELOPMENTPACKAGES[@]}" 2>errors)
			# Woopsie, Repo issue?  Let's rectify.
			if [[ -s "errors" ]]; then
				FullBar
				Encapsulate "Broken packages detected, Rectifying."
				# Build a array of good packages rip out the bad packages.
				# Break out a nested for loop.
				for EACH in "${DEVELOPMENTPACKAGES[@]}";
				do
					CHECKFORERROR=$(grep -i "${EACH}"  "errors")
					if ! [[ "${CHECKFORERROR}" ]]; then
						CLEANPACKAGES[${INDEX}]="${EACH}"
						INDEX=$((INDEX + 1))
					else
						Encapsulate "Package: ${EACH} is broken and will not be installed."
					fi
				done
				FullBar
				if [[ "${RECOMMENDS^^}" == "NO" ]]; then
					apt-get install -y -f --allow-unauthenticated --no-install-recommends "${CLEANPACKAGES[@]}"
				else
					apt-get install -y -f "${CLEANPACKAGES[@]}"
				fi
			else
				Center "All packages for ${DISTTYPE}, were successfully installed."
			fi
			#Encapsulate "Installing PyCharm"
			#snap install pycharm-community --classic
			FullBar;;
		extra) # Find the offending package(s) that are broken / missing. Redirect error output to a file to parse latter.
			# Test to see if we have broken packages.
			(apt-get install -y -f "${EXTRAPACKAGES[@]}" 2>errors)
			# Woopsie, Repo issue?  Let's rectify.
			if [[ -s "errors" ]]; then
				FullBar
				Encapsulate "Broken packages detected, Rectifying."
				# Build a array of good packages rip out the bad packages.
				# Break out a nested for loop.
				for EACH in "${EXTRAPACKAGES[@]}";
				do
					CHECKFORERROR=$(grep -i "${EACH}"  "errors")
					if ! [[ "${CHECKFORERROR}" ]]; then
						CLEANPACKAGES[${INDEX}]="${EACH}"
						INDEX=$((INDEX + 1))
					else
						Encapsulate "Package: ${EACH} is broken and will not be installed."
					fi
				done
				FullBar
				if [[ "${RECOMMENDS^^}" == "NO" ]]; then
					apt-get install -y -f --allow-unauthenticated --no-install-recommends "${CLEANPACKAGES[@]}"
				else
					apt-get install -y -f "${CLEANPACKAGES[@]}"
				fi
				apt-get remove --purge -y -f mate-terminal mate-terminal-common
				if [[ -f "/usr/bin/pluma" ]]; then
					FullBar
					Encapsulate "Setting Pluma as default editor."
					update-alternatives --install /usr/bin/gnome-text-editor gnome-text-editor /usr/bin/pluma 15
					update-alternatives --install /usr/bin/editor editor /usr/bin/pluma 15
					if [[ -f "/usr/bin/gedit" ]]; then
						update-alternatives --remove gnome-text-editor /usr/bin/gedit
						update-alternatives --auto gnome-text-editor
					fi
				fi
			else
				if [[ -f "/usr/bin/pluma" ]]; then
					FullBar
					Encapsulate "Setting Pluma as default editor."
					update-alternatives --install /usr/bin/gnome-text-editor gnome-text-editor /usr/bin/pluma 15
					update-alternatives --install /usr/bin/editor editor /usr/bin/pluma 15
					if [[ -f "/usr/bin/gedit" ]]; then
						update-alternatives --remove gnome-text-editor /usr/bin/gedit
						update-alternatives --auto gnome-text-editor
					fi
				fi
				Center "All packages for ${DISTTYPE}, were successfully installed."
			fi;;
		lite)	# Find the offending package(s) that are broken / missing. Redirect error output to a file to parse latter.
			# Test to see if we have broken packages.
			(apt-get install -y -f "${LITEPACKAGES[@]}" 2>errors)
			# Woopsie, Repo issue?  Let's rectify.
			if [[ -s "errors" ]]; then
				FullBar
				Encapsulate "Broken packages detected, Rectifying."
				# Build a array of good packages rip out the bad packages.
				# Break out a nested for loop.
				for EACH in "${LITEPACKAGES[@]}";
				do
					CHECKFORERROR=$(grep -i "${EACH}"  "errors")
					if ! [[ "${CHECKFORERROR}" ]]; then
						CLEANPACKAGES[${INDEX}]="${EACH}"
						INDEX=$((INDEX + 1))
					else
						Encapsulate "Package: ${EACH} is broken and will not be installed."
					fi
				done
				FullBar
				if [[ "${RECOMMENDS^^}" == "NO" ]]; then
					apt-get install -y -f --allow-unauthenticated --no-install-recommends "${CLEANPACKAGES[@]}"
				else
					apt-get install -y -f "${CLEANPACKAGES[@]}"
				fi
			else
				Center "All packages for ${DISTTYPE}, were successfully installed."
			fi;;
		full)	(apt-get install -y -f "${FULLPACKAGES[@]}" 2>errors)
			# Woopsie, Repo issue?  Let's rectify.
			if [[ -s "errors" ]]; then
				FullBar
				Encapsulate "Broken packages detected, Rectifying."
				# Build a array of good packages rip out the bad packages.
				# Break out a nested for loop.
				for EACH in "${FULLPACKAGES[@]}";
				do
					CHECKFORERROR=$(grep -i "${EACH}"  "errors")
					if ! [[ "${CHECKFORERROR}" ]]; then
						CLEANPACKAGES[${INDEX}]="${EACH}"
						INDEX=$((INDEX + 1))
					else
						Encapsulate "Package: ${EACH} is broken and will not be installed."
					fi
				done
				FullBar
				if [[ "${RECOMMENDS^^}" == "NO" ]]; then
					apt-get install -y -f --allow-unauthenticated --no-install-recommends "${CLEANPACKAGES[@]}"
				else
					apt-get install -y -f "${CLEANPACKAGES[@]}"
				fi
			else
				Center "All packages for ${DISTTYPE}, were successfully installed."
			fi;;
		server)	(apt-get install -y -f "${SERVERPACKAGES[@]}" 2>errors)
			# Woopsie, Repo issue?  Let's rectify.
			if [[ -s "errors" ]]; then
				FullBar
				Encapsulate "Broken packages detected, Rectifying."
				# Build a array of good packages rip out the bad packages.
				# Break out a nested for loop.
				for EACH in "${SERVERPACKAGES[@]}";
				do
					CHECKFORERROR=$(grep -i "${EACH}"  "errors")
					if ! [[ "${CHECKFORERROR}" ]]; then
						CLEANPACKAGES[${INDEX}]="${EACH}"
						INDEX=$((INDEX + 1))
					else
						Encapsulate "Package: ${EACH} is broken and will not be installed."
					fi
				done
				FullBar
				if [[ "${RECOMMENDS^^}" == "NO" ]]; then
					apt-get install -y -f --allow-unauthenticated --no-install-recommends "${CLEANPACKAGES[@]}"
				else
					apt-get install -y -f "${CLEANPACKAGES[@]}"
				fi
			else
				Center "All packages for ${DISTTYPE}, were successfully installed."
			fi
			# 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;;
		minimal-server) (apt-get install -y -f "${MINIMALPACKAGES[@]}" 2>errors)
			# Woopsie, Repo issue?  Let's rectify.
			if [[ -s "errors" ]]; then
				FullBar
				Encapsulate "Broken packages detected, Rectifying."
				# Build a array of good packages rip out the bad packages.
				# Break out a nested for loop.
				for EACH in "${MINIMALPACKAGES[@]}";
				do
					CHECKFORERROR=$(grep -i "${EACH}"  "errors")
					if ! [[ "${CHECKFORERROR}" ]]; then
						CLEANPACKAGES[${INDEX}]="${EACH}"
						INDEX=$((INDEX + 1))
					else
						Encapsulate "Package: ${EACH} is broken and will not be installed."
					fi
				done
				FullBar
				if [[ "${RECOMMENDS^^}" == "NO" ]]; then
					apt-get install -y -f --allow-unauthenticated --no-install-recommends "${CLEANPACKAGES[@]}"
				else
					apt-get install -y -f "${CLEANPACKAGES[@]}"
				fi
			else
				Center "All packages for ${DISTTYPE}, were successfully installed."
			fi;;
		gamers)	(apt-get install -y -f "${GAMERSPACKAGES[@]}" 2>errors)
			# Woopsie, Repo issue?  Let's rectify.
			if [[ -s "errors" ]]; then
				FullBar
				Encapsulate "Broken packages detected, Rectifying."
				# Build a array of good packages rip out the bad packages.
				# Break out a nested for loop.
				for EACH in "${GAMERSPACKAGES[@]}";
				do
					CHECKFORERROR=$(grep -i "${EACH}" "errors")
					if ! [[ "${CHECKFORERROR}" ]]; then
						CLEANPACKAGES[${INDEX}]="${EACH}"
						INDEX=$((INDEX + 1))
					else
						Encapsulate "Package: ${EACH} is broken and will not be installed."
					fi
				done
				FullBar
				if [[ "${RECOMMENDS^^}" == "NO" ]]; then
					apt-get install -y -f --allow-unauthenticated --no-install-recommends "${CLEANPACKAGES[@]}"
				else
					apt-get install -y -f "${CLEANPACKAGES[@]}"
				fi
			else
				Center "All packages for ${DISTTYPE}, were successfully installed."
			fi;;
		allgames) (apt-get install -y -f "${ALLGAMES[@]}" 2>errors)
			# Woopsie, Repo issue?  Let's rectify.
			if [[ -s "errors" ]]; then
				FullBar
				Encapsulate "Broken packages detected, Rectifying."
				# Build a array of good packages rip out the bad packages.
				# Break out a nested for loop.
				for EACH in "${ALLGAMES[@]}";
				do
					CHECKFORERROR=$(grep -i "${EACH}" "errors")
					if ! [[ "${CHECKFORERROR}" ]]; then
						CLEANPACKAGES[${INDEX}]="${EACH}"
						INDEX=$((INDEX + 1))
					else
						Encapsulate "Package: ${EACH} is broken and will not be installed."
					fi
				done
				FullBar
				if [[ "${RECOMMENDS^^}" == "NO" ]]; then
					apt-get install -y -f --allow-unauthenticated --no-install-recommends "${CLEANPACKAGES[@]}"
				else
					apt-get install -y -f "${CLEANPACKAGES[@]}"
				fi
			else
				Center "All packages for ${DISTTYPE}, were successfully installed."
			fi;;
		custom) # Find the offending package(s) that are broken / missing. Redirect error output to a file to parse latter.
			# Test to see if we have broken packages.
			if [[ "${RECOMMENDS^^}" == "NO" ]]; then
			    apt-get install -f -y --allow-unauthenticated --no-install-recommends "${CUSTOMPACKAGES[@]}" 2>errors
			else
			    apt-get install -f -y --allow-unauthenticated "${CUSTOMPACKAGES[@]}" 2>errors
			fi
			# Woopsie, Repo issue?  Let's rectify.
			if [[ -s "errors" ]]; then
				FullBar
				Encapsulate "Broken packages detected, Rectifying."
				# Build a array of good packages rip out the bad packages.
				# Break out a nested for loop.
				for EACH in "${CUSTOMPACKAGES[@]}";
				do
					if [[ -f "errors" ]]; then
						CHECKFORERROR=$(grep -i "${EACH}" "errors")
					fi
					if ! [[ "${CHECKFORERROR}" ]]; then
						CLEANPACKAGES[${INDEX}]="${EACH}"
						INDEX=$((INDEX + 1))
					else
						Encapsulate "Package: ${EACH} is broken and will not be installed."
					fi
				done
				FullBar
				if [[ "${RECOMMENDS^^}" == "NO" ]]; then
    				apt-get install -f -y --allow-unauthenticated --no-install-recommends "${CLEANPACKAGES[@]}"
    			else
    			    apt-get install -f -y --allow-unauthenticated "${CLEANPACKAGES[@]}"
    			fi
			else
				Center "All packages for ${DISTTYPE}, were successfully installed."
			fi;;
	esac
	if [[ -f "errors" ]]; then
		rm "errors"
	fi
}

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
}


Session () {
	#Turn off case sensitivity
	shopt -s nocasematch

	LIGHTDM="${PACKAGE}/usr/share/ultimate_edition/lightdm-ultimate.conf"
	DMRC="${PACKAGE}/etc/skel/.dmrc"
	for PARAM in "$@"
	do
		for EACH in "${EXTRADE[@]}"
		do
			if [[ "${DEBUG}" ]]; then
				echo "DEBUG: Comparing ${PARAM} to ${EACH}"
			fi
			if [[ "${EACH}" == "${PARAM}" ]]; then
				DEFAULTDE="${EACH}"
				if [[ "${DEBUG}" ]]; then
					echo "DEBUG: found ${PARAM} to ${EACH}"
				fi
			fi
		done
	done
    CONTAINS=$(echo "$*" | grep -i "list")
    if [[ "${CONTAINS}" ]]; then
        Center "Installed sessions:"
		SESSIONS=(/usr/share/xsessions/*)
		if ! [[ "${SESSIONS}" ]]; then
			Encapsulate "NONE, Minimal server"
		else
			for EACH in "${SESSIONS[@]}"
			do
				Encapsulate "${EACH}"
			done
		fi
    fi
	# Default desktop environment specified?
	XINITRC="/etc/skel/.xinitrc"
	if [[ "${DEFAULTDE}" ]]; then
		DEFAULTDE=$(echo "${DEFAULTDE}" | tr '[:upper:]' '[:lower:]')
		Encapsulate "Setting ${DEFAULTDE} as default desktop environment (DE)."
		case "${DEFAULTDE}" in
			deepin) if  [[ -f "${LIGHTDM}" ]]; then
						sed -i "s/user-session=.*/lightdm-deepin-greeter/g" "${LIGHTDM}"
					else
						echo "[SeatDefaults]" > "${LIGHTDM}"
						echo "user-session=lightdm-deepin-greeter" >> "${LIGHTDM}"
					fi
					if [[ -f "${DMRC}" ]]; then
						sed -i "s/Session=.*/Session=startdde/g" "${DMRC}"
						echo "exec ubuntudde" > "${XINITRC}"
					else
						echo "[Desktop]" > "${DMRC}"
						echo "Session=startdde" >> "${DMRC}"
						echo "exec startdde" > "${XINITRC}"
					fi;;
			pantheon) INSTALLED=$(dpkg-query -l "elementary-desktop" | grep "ii" 2>/dev/null);
					 if ! [[ "${INSTALLED}" ]]; then Center "INSTALLING PANTHEON DE";
					 	FullBar;
					 	apt-get install -f -y --allow-unauthenticated --no-install-recommends elementary-desktop;
					 fi;
					 LightDM;
					 Ubiquity gtk;
					 BaseApplications;;
			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}"
						echo "exec budgie-desktop" > "${XINITRC}"
					else
						echo "[Desktop]" > "${DMRC}"
						echo "Session=budgie-desktop" >> "${DMRC}"
						echo "exec budgie-desktop" > "${XINITRC}"
					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;;

            enlightenment)
						echo "#!/bin/sh" > "${XINITRC}"
                        echo "exec /usr/bin/enlightenment" >> "${XINITRC}"
                        if  [[ -f "${LIGHTDM}" ]]; then
    						sed -i "s/user-session=.*/user-session=enlightenment/g" "${LIGHTDM}"
					else
						echo "[SeatDefaults]" > "${LIGHTDM}"
						echo "user-session=enlightment" >> "${LIGHTDM}"
					fi
					if [[ -f "${DMRC}" ]]; then
						sed -i "s/Session=.*/Session=enlightenment/g" "${DMRC}"
					else
						echo "[Desktop]" > "${DMRC}"
						echo "Session=enlightenment" >> "${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
	FullBar
}

Help () {
	CONTAINS=$(echo "$*" | grep -w '\-h\|\-\-help')
	#echo "DEBUGGING HELP FUNCTION: 1:${1} 2:${2} 3:${3} CONTAINS:${CONTAINS}"
	if ! [[ "${3}" == "" && "${CONTAINS}" ]]; then
		if [[ "${2}" != "" ]]; then
			PRAM="${2}"
		else
			PRAM="ALL"
		fi
	fi
	if [[ "${CONTAINS}" ]]; then
		if [[ "${3}" == "" ]]; then
			VersionDump
		fi
		if [[ "${2}" != "" ]]; then
			PRAM="${2}"
		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 "  -a   --add            adds application(s) / type(s)"
		Encapsulate "  -d   --dist-upgrade   distro upgrades current Operating System"
		Encapsulate "  -g   --grub-session   select default Grub selection"
		Encapsulate "  -h   --help           this help message"
		Encapsulate "  -k   --kde            sets KDE's splash to current version"
		Encapsulate "  -r   --repositories   adds Ultimate Edition & various repositories"
		Encapsulate "  -s   --session        set default session"
		Encapsulate "  -S   --size           display size of installed packages"
		Encapsulate "  -t   --themes         installs all Ultimate Edition Themes"
		Encapsulate "  -U   --ultimate       Brings UE when all else fails."
		Encapsulate "  -u   --upgrade        upgrades current Operating System"
		Encapsulate "  -v   --version        dump version info and exit"
		Encapsulate " "
		FullBar
		Center "${PROGNAME} --help [COMMAND] for further information.";;
		ALL|s|session)
		Encapsulate " "
		Encapsulate "Usage session <OPTION>;"
		FullBar
		Encapsulate "${PROGNAME} -s <OPTION>"
		FullBar
		Encapsulate "Invokes ${PROGNAME} to set the default session or list currently installed session(s)."
		Encapsulate "Options are:"
        INCREMENT=0
        TOTAL="${#EXTRADE[@]}"
        FULLMONTY="LIST, "
		for EACH in "${EXTRADE[@]}";
		do
            INCREMENT=$((INCREMENT+1))
            if [[ "${INCREMENT}" != "${TOTAL}" ]]; then
    			FULLMONTY="${FULLMONTY} ${EACH}, "
            else
                FULLMONTY="${FULLMONTY} ${EACH}."
            fi
		done
        Encapsulate "${FULLMONTY}"
		Encapsulate "Example: ${PROGNAME} -s budgie"
        Encapsulate "Will set budgie as the default session for the Operating System."
        FullBar;;
        ALL|t|themes)
		Encapsulate " "
		Encapsulate "Usage themes;"
		FullBar
		Encapsulate "${PROGNAME} -t [OPTIONAL]"
		FullBar
		Encapsulate "Invokes ${PROGNAME} to download all Ultimate Edition themes or"
        Encapsulate "download / install a [OPTIONAL] theme."
        Encapsulate "Example: ${PROGNAME} --themes 5.7"
        Encapsulate "Will download & install only Ultimate Edition 5.7 theme."
        FullBar;;
		ALL|d|dist-upgrade)
		Encapsulate " "
		Encapsulate "Usage dist-upgrade;"
		FullBar
		Encapsulate "${PROGNAME} -d"
		FullBar
		Encapsulate "Invokes ${PROGNAME} to distribution upgrade current Operating system.";;
		ALL|a|add)
		Encapsulate " "
		Encapsulate "Usage add <OPTION>;"
		FullBar
		Encapsulate "${PROGNAME} -a <OPTION>"
		FullBar
		Encapsulate "Invokes ${PROGNAME} to add <OPTION> to the target Operating system."
		Encapsulate "Valid arguments are as follows:"
		Encapsulate "wine, gamers, lite, full, server, minimal-server, extra, developer"
        Encapsulate ""
        Encapsulate "Other valid <Options> to add desktop environments:"
        INCREMENT=0
        TOTAL="${#EXTRADE[@]}"
        FULLMONTY=""
		for EACH in "${EXTRADE[@]}";
		do
            INCREMENT=$((INCREMENT+1))
            if [[ "${INCREMENT}" != "${TOTAL}" ]]; then
    			FULLMONTY="${FULLMONTY} ${EACH}, "
            else
                FULLMONTY="${FULLMONTY} ${EACH}."
            fi
		done
        Encapsulate "${FULLMONTY}"
        Encapsulate ""
		Encapsulate "Example: ${PROGNAME} --add gamers"
		Encapsulate "Will add all the games into your current build."
        FullBar;;
		ALL|u|upgrade)
		Encapsulate " "
		Encapsulate "Usage upgrade;"
		FullBar
		Encapsulate "${PROGNAME} -u [ISO]"
		FullBar
		Encapsulate "Will mount and extract [ISO] image and invoke distribution upgrade."
		Encapsulate "The [ISO] is only [OPTIONAL] because it will process folders as well."
		Encapsulate "Example: ${PROGNAME} --upgrade ultimate-edition-3.4-x64.iso";;
		ALL|v|version)
		Encapsulate " "
		Encapsulate "Usage version;"
		FullBar
		Encapsulate "${PROGNAME} -v"
		FullBar
		Encapsulate "Displays ${PROGNAME}'s version number and exits.";;
		ALL|h|help|\?)
		Encapsulate " "
		Encapsulate "Useage Help [COMMAND];"
		FullBar
		Encapsulate "${PROGNAME} -h [COMMAND]"
		FullBar
		Encapsulate "Displays this message. For futher information ${PROGNAME} help [COMMAND]"
		Encapsulate "or refer to the manpages.\\n"
		Encapsulate "man ${PROGNAME}"
		Encapsulate " "
		Encapsulate "Example: ${PROGNAME} -h version"
		Encapsulate "Will display help about the command version"
	esac
	exit 0
}

DarkenUbuiquity () {
    Ultimate=$(lsb_release -a | grep -i 'Ultimate')
    Convert=$(type -p convert)
    VersionDump
    if ! [[ "$Convert" ]]; then
        Encapsulate "Installing Convert."
        apt-get install -f -y imagemagick
    fi
    Center "TESTING: We are testing function DarkenUbiquity"
    # bust out an array, I am used to them changing things w/o thought of other programmers / O/S developers.  Makes it easier to wipe out thier decisions. Inform the enduser.
    Encapsulate "I am used to infinite wisdom (Ubuntu) making changes with disregard.  See code Function DarkenUbuiquity in tmmount."
    declare -a UbiquityImages=( "/usr/share/ubiquity/qt/images/main.png" "/usr/share/ubiquity/qt/images/breadcrumb_ltr.png" "/usr/share/ubiquity/qt/images/breadcrumb_rtl.png" );
    UbiquityLogo="/usr/share/ubiquity/qt/images/branding.svgz"
    for EACH in "${UbiquityImages[@]}"
    do
        if [[ -f "${EACH}" ]]; then
            Encapsulate "File: ${EACH} exists, converting to a dark theme with transparency."
            Encapsulate "If you want to complain about this dirty hack, please file a bug with Ubiquity and their lack of supporting dark themes since 2014."
            Encapsulate "I no longer file bug reports.  I fix or work around them as in this case."
            Encapsulate "Bug info: https://bugs.launchpad.net/ubuntu/+source/ubiquity/+bug/1343651"
        fi
    done
    if [[ -f "$UbiquityLogo" && "$Ultimate" ]]; then
        Encapsulate "Theme based logo found & Ultimate Edition based O/S, please wait logo stamping..."
        if [[ -f "/usr/share/ultimate_edition/logo.svgz" ]]; then
            Encapsulate "Logo detected, replacing with Ultimate Edition Logo."
            cp "/usr/share/ultimate_edition/logo.svgz" "$UbiquityLogo"
        fi
    fi
}

# Scans and sets KDE splash via various resolutions
KDESPLASH () {
	INFOLDER="${PWD}"
	RESOLUTIONS=( "1024x768" "1280x1024" "1280x800" "1366x768" "1440x900" "1600x1200" "1680x1050" "1920x1080" "1920x1200" "2560x1440" "2560x1600" "3200x1800" "3200x2000" "3840x2160" "5120x2880" );
	COUNTDOTS=$(echo "${DISTREL}" |grep -o "\\." | wc -l)
	if [[ "${DISTREL}" ]]; then
		if [[ "${COUNTDOTS}" -gt 1 ]]; then
			LONGVERSION="${DISTREL%.*}"
			SHORTVERSION="${LONGVERSION}"
			Encapsulate "Version detected as: ${DISTREL} (${SHORTVERSION})"
			DISTREL="${SHORTVERSION}"
		else
			Encapsulate "Version detected as: ${DISTREL}"
		fi
	else
		Error "Version not detected. Exiting."
		exit 1;
	fi

    SOURCEFILE="/usr/share/wallpapers/Ultimate_Edition_${DISTREL}.png"
	DESTFOLDER="/usr/share/kde4/apps/ksplash/Themes/Default/"
    if [[ -f "/usr/share/sddm/themes/breeze/components/artwork/background.png" ]]; then
        Encapsulate "Newer version of KDE detected. Setting up as required."
        DESTFOLDER="/usr/share/sddm/themes/breeze/components/artwork/"
        cd "${DESTFOLDER}" || exit 1;
        STRIPPEDSLASH="background.png"
        Encapsulate "Converting image ${SOURCEFILE} in ${PWD} to 3840×2160! to ${DESTFOLDER}${STRIPPEDSLASH}"
        convert "${SOURCEFILE}" -resize 3840x2160! -quality 100 -strip "${DESTFOLDER}${STRIPPEDSLASH}"
        Encapsulate "Success, exiting."
        exit 0;
    fi
	CONVERSION=$(type -p convert)
	DESTFOLDER="/usr/share/wallpapers/Ultimate_Edition_${DISTREL}/contents/"
	if [[ "${SOURCEFILE}" ]]; then
		if ! [[ -d "/usr/share/wallpapers/Ultimate_Edition_${DISTREL}/contents/images/" ]]; then
			Encapsulate "Creating Wallpaper Folder."
			mkdir -p "/usr/share/wallpapers/Ultimate_Edition_${DISTREL}/contents/images/"
		fi
	fi
	if [[ "${CONVERSION}" && -f "${SOURCEFILE}" && -d "${DESTFOLDER}" ]]; then
		Encapsulate "Copying Wallpaper: ${SOURCEFILE} to ${DESTFOLDER}/screenshot.png."
		cp "${SOURCEFILE}" "${DESTFOLDER}/screenshot.png"
	    cd "${DESTFOLDER}" || exit 1;
		SOURCEFILE="screenshot.png"
		DESTFOLDER="images/"
	    for EACH in "${RESOLUTIONS[@]}"
	    do
	        Encapsulate "Converting image ${SOURCEFILE} at ${PWD} to ${DESTFOLDER}/${EACH}.jpg"
	        convert "${SOURCEFILE}" -resize "${EACH}!" -quality 100 -strip "${DESTFOLDER}/${EACH}.jpg"
	    done
{
		echo '[Desktop Entry]'
		echo "Name=Ultimate_Edition_${DISTREL}"
		echo "Name[en_GB]=Ultimate_Edition_${DISTREL}"
		echo ''
		echo "X-KDE-PluginInfo-Name=Ultimate_Edition_${DISTREL}"
		echo 'X-KDE-PluginInfo-Author=Glenn Cady'
		echo 'X-KDE-PluginInfo-Email=theemahn@gmail.com'
		echo 'X-KDE-PluginInfo-License=GPL2.0'
}  > metadata.desktop
	    Center "Ksplash will be themed in ${DISTREL}"
	else
	    if ! [[ "$CONVERSION" ]]; then
	    	Error "Imagemagick is not installed, ksplash will not be themed."
	    fi
	    if ! [[ "${SOURCEFILE}" ]]; then
	    	Error "Ultimate Edition ${DISTREL} theme is not installed."
	    fi
	    if ! [[ "${DESTFOLDER}" ]]; then
	    	Error "Ksplash has not been installed, or has not been programmed. Not themeing."
	    fi
	    Error "Ksplash will not be themed."
    fi
    if [[ -d "${INFOLDER}" ]]; then
    	cd "${INFOLDER}" || exit 1;
    fi
    if [[ "${DISTREL}" ]]; then
        DarkenUbuiquity
    fi
}

AddChoice () {
    if [[ "${DEBUG}" ]]; then
	    echo "debug: $* | 1:${1} |2: ${2} |3: ${3}"
    fi
	if [[ "${2}" ]]; then
		case "${2}" in
			wine) WineUp; exit 0;;
			compiz) Compiz; exit 0;;
			gamers) DISTTYPE='gamers'; QuestForSpeed; exit 0;;
			lite) DISTTYPE='lite'; QuestForSpeed; exit 0;;
			full) DISTTYPE='full'; QuestForSpeed; exit 0;;
			server) DISTTYPE='server'; QuestForSpeed; exit 0;;
			developer) DISTTYPE='developer'; QuestForSpeed; exit 0;;
			basepackages) DISTTYPE='basepackages'; QuestForSpeed; exit 0;;
			minimal-server) DISTTYPE='minimal-server'; QuestForSpeed; exit 0;;
			extra) DISTTYPE='extra'; QuestForSpeed; exit 0;;
		esac
        declare -i INCREMENT
        INCREMENT=0
        shopt -s nocasematch
    	for EACH in "${EXTRADE[@]}"
		do
			if [[ "${DEBUG}" ]]; then
				echo "DEBUG: Comparing ${2} to ${EACH}"
			fi
			if [[ "${EACH}" == "${2}" ]]; then
				INSTALLDE="${DEADD[${INCREMENT}]}"
				if [[ "${DEBUG}" ]]; then
					echo "DEBUG: found ${2} to ${EACH}"
				fi
			fi
            INCREMENT=$(("${INCREMENT}" +1))
		done
        if [[ "${INSTALLDE}" ]]; then
            Encapsulate "INSTALLING ${INSTALLDE}"
            apt-get install -y -f "${INSTALLDE}"
            INSTALLED=$(dpkg-query -l "${INSTALLDE}" 2>/dev/null | grep "ii" 2>/dev/null)
            if [[ "${INSTALLED}" ]]; then
                Encapsulate "${INSTALLDE} was sucessfully installed."
                Encapsulate "${PROGNAME} --session ${2}, to set this environment as the default session.  See ${PROGNAME} --help session for further information."
                FullBar
                exit 0;
            else
                Error "An error occured installing ${INSTALLDE}."
                exit 1;
            fi
        else
            Error "[Option] ${2} not found."
        fi
	else
		Help Add
		exit 0
	fi
}

LiquidCrack () {
    CUSTOMPACKAGES="*"
	REVERT="${RECOMMENDS}"
    RECOMMENDED="YES"
    DISTTYPE="custom"
    QuestForSpeed
    CUSTOMPACKAGES=""
    RECOMMENDED="${REVERT}"
    DISTTYPE=""
    exit 0;
}

InstalledSize () {
	dpkg-query -W --showformat='${Installed-Size;10}\t${Package}\n' | sort -k1,1n
}

Accelerate () {
	apt-get install --yes --assume-yes wget linux-base
	Encapsulate "Scrapping bloatware: apt-get remove --purge linux-headers-5.4.0-26-generic linux-headers-5.4.0-26-generic linux-headers-5.4.0-46 linux-headers-5.4.0-26 linux-image-5.4.0-26-generic linux-modules-5.4.0-26-generic linux-modules-extra-5.4.0-26-generic fonts-noto*"
	apt-get remove --purge --yes --assume-yes linux-{headers,image,modules}-5.4* fonts-noto* dkms*
	if [[ "${2}" == "L" ]]; then
		KERNELS=( "linux-headers-5.8.5-050805-lowlatency_5.8.5_amd64.deb" "linux-headers-5.8.5-050805_5.8.5_all.deb" "linux-image-unsigned-5.8.5-050805-lowlatency_amd64.deb" "linux-modules-5.8.5-050805-lowlatency_5.8.5_amd64.deb" );
	else
		KERNELS=( "linux-headers-5.8.5_all.deb" "linux-image-unsigned-5.8.5_amd64.deb" "linux-headers-5.8.5_amd64.deb" "linux-modules-5.8.5_amd64.deb" );
	fi
	cd /tmp/
	rm -R *
	for EACH in "${KERNELS[@]}"
	do
		wget "http://os-builder.com/KERNEL/${EACH}"
	done
	#tmmount -d
}

Strip () {
	# Set defaults set an integer for # of packages installed.
	declare -i PACKAGESINSTALLED;
	PACKAGESINSTALLED=0
	# Build a database of each and every package installed.
	declare -a INSTALLEDPACKAGES=();  # break out an array...  Sort by size
	declare -a TEMPVAR=();
	OIFS=$IFS
	#IFS=$'\n'
	TEMPVAR=$(dpkg-query -W --showformat='${Installed-Size;10}\t${Package}\n' | sort -k1,1n | awk '{ print $2 }')
	IFS=$'\n' INSTALLEDPACKAGES=($TEMPVAR)
	for EACH in "${INSTALLEDPACKAGES[@]}";
	do
		ISINSTALLED=$((dpkg-query -l "${EACH}" | grep "ii")2>/dev/null)
		if [[ "${ISINSTALLED}" ]]; then
			((PACKAGESINSTALLED = PACKAGESINSTALLED +1))
			echo "${PACKAGESINSTALLED}. ${EACH}"
			apt-get autoremove --purge "${EACH}"
		fi
	done
	IFS=$OIFS
}

case "${1}" in
	-a|--add) AddChoice "$@"; exit 0;;
	-A|--accelerate) Accelerate "$@"; exit 0;; # Hidden & undocumented feature.
	-b|--basepackages) AddChoice "basepackages"; exit 0;;
	-c|--chrome) Chrome "$@"; exit 0;; # Hidden & undocumented feature.
	-d|--dist-upgrade) DistUpgrade "$@"; exit 0;;
	-f|--firefox) FireFox "$@"; exit 0;; # Hidden & undocumented feature.
	-g|--grub-session) GrubSession "$@"; exit 0;;
	-h|--help|-\?) Help "$@"; exit 0;; # TODO: Enhance this section.
	-k|--kde) KDESPLASH "$@"; exit 0;;
	-K|--kernel) KernelSanders "$@"; exit 0;; # Hidden & undocumented feature.
	-l|--liquid-crack) LiquidCrack "$@"; exit 0;; # Hidden & undocumented feature.
	-r|--repositories) Repositories "$@"; exit 0;;
	-s|--session) Session "$@"; exit 0;;
	-S|--size) InstalledSize "$@"; exit 0;;
	-y|--strip) Strip "$@"; exit 0;; # Hidden & undocumented feature.
	-t|--themes) Themes "$@"; exit 0;;
	-U|--ultimate) UltimateApps "$@"; Themes "$@"; exit 0;;
	-u|--upgrade) UpgradeISO "$@"; exit 0;;
	-v|--version) VersionDump "$@"; exit 0;;
	-z|--test) DarkenUbuiquity "$@"; exit 0;; # Hidden & undocumented feature.
	*) Help; exit 0;;
esac
