#!/bin/bash
# ==============================================================================
# title			:usplash-builder
# description	:Builds Usplash debian packages.
# author		:theemahn <theemahn@ultimateedition.info>
# date			:06/15/2016
# version		:1.9.7
# usage			:usplash-builder --help
# manual		:man usplash-builder
# 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	Updated donors list and usplash application to better columinize data
#			Bumped internal data to version 100
#	1.9.4	Fixed installation of splash.
#
#			Added subsets (gamers, lite etc.)
#
#	1.9.5	Bumped internal data to version 999
#			Added support for detection of default DE's
#
#	1.9.6	Added support for UE 5.0 & 5.1
#
#	1.9.7	Closed the LTS (Long Term Supported) Gap.
#			Shellchecked, added stand-alone functionality
#	1.9.8	Version bump
#	1.9.9	Version bump, will most likely update splashes in this release.
#	2.0.3   Fixed Kubuntu / Ubuntu detection and creation.
#	2.0.5	Added support KDE /Gnome, mate all non-KDE... detection
#	2.0.7	Added initial support for "Jammy Jellyfish" / Ultimate Edition 7.4 & 7.5
# ==============================================================================
# Version Control

APPNAME="TheeMahn O/S Builder"
PROGNAME="usplash-builder"
BUILDDATE="12/02/2021"
VERSION="2.0.7"
EXEC="${PWD}"
WEBSITE="os-builder.com"
AUTHOR="TheeMahn"
EMAIL="<$AUTHOR@${WEBSITE}>"

source /usr/share/ultimate_edition/ultimate-common

# Check if user would like to debug, Yes, I am not infallible. ;)
DEBUG=$(echo "$*" | grep -i "debug")

BuildUsplash(){
	# ${1} FOLDER TO PROCESS ${2} DONATION LOG
	#Set defaults
	DISTRO="Ultimate Edition"
	DONORSFILE=$(echo "$3" | grep -i '.csv')

	if ! [[ "${DONORSFILE}" && -f "${DONORSFILE}" ]]; then
		DONORSFILE="donors.csv"
	fi

	VersionDump
	if [[ "$DEBUG" ]]; then
		echo "DEBUGGING: $*"
	fi

	if [[ "${1}" == "" ]]; then
		Error "Please provide switch.  Example:"
		Error "usplash-builder 5.0 lite"
		exit 1;
	fi

	LITE=$(echo "$*" | grep -i "lite")
	GAMERS=$(echo "$*" | grep -i "gamers")
	SERVER=$(echo "$*" | grep -i "server")
	MINIMAL=$(echo "$*" | grep -i "minimal")
	if [[ "${1}" == "-b" || "${1}" == "--build" ]]; then
		shift
	fi
	BASEBUILD="${1}"
	CVERSION="${1}"
	BLEN="${#BASEBUILD}"

	if [[ "$BLEN" -le 3 ]]; then
		BASEBUILD="${CVERSION%.*}"
	else
		BASEBUILD="${CVERSION}"
	fi

	for OST in "${UEARRAY[@]}"
	do
		if [[ "$OST" == "${BASEBUILD}" ]]; then
			DIST="${OSARRAY[$array_counter]}"
			FULLNAME="${DISTARRAY[$array_counter]}"
		fi
		array_counter=$((array_counter + 1))
	done
	if ! [[ "${FULLNAME}" ]]; then
		array_counter=0
		BASEBUILD="${CVERSION}"
		for OST in "${UEARRAY[@]}"
		do
			if [[ "$OST" == "${BASEBUILD}" ]]; then
				DIST="${OSARRAY[$array_counter]}"
				FULLNAME="${DISTARRAY[$array_counter]}"
			fi
			array_counter=$((array_counter + 1))
		done
	fi

	#Check for LTS
	array_counter=0
	LTS=""
	declare -i LENGTH;
	LENGTH="${#CVERSION}"
    if [[ "$DEBUG" ]]; then
	    echo "DEBUGGING LENGTH: ${LENGTH}"
    fi
	for OST in "${ISLTS[@]}"
	do
		if [[ "${CVERSION}" == "$OST" || "${LENGTH}" -ge 4 ]]; then
			LTS="YES"
		fi
		array_counter=$((array_counter + 1))
	done

	EVENODD="${VERSIONCHECK##*.}"
	if ! [[ "$(( EVENODD % 2))" -ne 0 ]]; then
		DTYPE="Standard"
		PACKAGE="ubiquity-slideshow-ubuntu_999_all"
	else
		DTYPE="Kubuntu Build"
		PACKAGE="ubiquity-slideshow-kubuntu_999_all"
	fi
	COMMANDISSUED=$(echo "$*" | tr '[:upper:]' '[:lower:]')
	DEFAULTDE=$(echo "${COMMANDISSUED}" | grep -i "defaultde=" | sed 's/^.*defaultde=//g' | cut -d' ' -f1)
	if [[ "${DEFAULTDE}" == "kde" ]]; then
		DTYPE="Kubuntu Build"
		PACKAGE="ubiquity-slideshow-kubuntu_999_all"
	fi

	#if [[ "${UBUNTU}" ]]; then
	#	OUTDISTRO="Ubuntu"
	#else
		OUTDISTRO="Ultimate Edition"
	#fi
	if [[ "${DTYPE}" ]]; then
		if [[ "${LONGVERSION}" ]]; then
			FULLNAME="${OUTDISTRO} ${LONGVERSION} ${DTYPE}"
		else
			FULLNAME="${OUTDISTRO} ${CVERSION} ${DTYPE}"
		fi
	fi
	DONORS="${DONORSFILE}"
	FullBar

	if [[ "${LITE}" ]]; then
		DTYPE="lite"
	fi
	Encapsulate "Operating System Output: ${OUTDISTRO}"
	if [[ "${LONGVERSION}" ]]; then
		Encapsulate "Operating System version requested: ${LONGVERSION}"
	else
		Encapsulate "Operating System version requested: ${CVERSION}"
	fi
	Encapsulate "Operating System distribution base: ${DIST}"
	Encapsulate "Distribution Long Name: ${FULLNAME}"
	Encapsulate "Distribution Type: ${DTYPE}"
    if [[ "${LTS}" ]]; then
        Encapsulate "LTS: Yes"
    else
        Encapsulate "LTS: No"
    fi
	if [[ "${DEFAULTDE}" ]]; then
		Encapsulate "Default desktop environment specified as: ${DEFAULTDE}"
	fi
	if [[ -f "${DONORSFILE}" ]]; then
		Encapsulate "Donors File: ${DONORSFILE} (exists)"
	else
		Encapsulate "Donors File: ${DONORSFILE} (non-existant, will pull from server / local)"
	fi
	FullBar
	Center "DEBIAN PACKAGE TO BUILD: ${PACKAGE}.deb"
	FullBar
	if [[ "${OUTDISTRO}" && "${LONGVERSION}" && "${DIST}" && "${FULLNAME}" && "${DTYPE}" && "${PACKAGE}" ]]; then
		Error "DEBUG: ${OUTDISTRO} || ${CVERSION} || ${DIST} || ${FULLNAME} || ${DTYPE} || ${PACKAGE} || ${LTS} || ${BASEBUILD}"
		Error "Please provide switch.  Example:"
		Error "usplash-builder --build 5.0 lite donors.csv"
		FullBar
		exit 1;
	fi
	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 ${2} ...";;
				* ) echo "Please answer y or n.";;
			esac
	fi

	#GENERIC UBIQUITY SPLASH
	if [[ -f "/usr/share/ultimate_edition/${PACKAGE}.tar.gz" && ! -d "${PACKAGE}" ]]; then
		Encapsulate "Pulling generic tar ${PACKAGE}.tar.gz"
		cp "/usr/share/ultimate_edition/${PACKAGE}.tar.gz" .
		Encapsulate "Extracting archive:"
		SUCCESS=$(tar xfv "${PACKAGE}.tar.gz")
		sync
		if [[ "${SUCCESS}" ]]; then
			Encapsulate "Success"
			rm "${PACKAGE}.tar.gz"
		else
			Error "ERROR in extraction."
			exit 1;
		fi
	else
		if [[ -d "${PACKAGE}" ]]; then
			Encapsulate "Previous build exists. Continuing."
		else
			Error "CRITICAL ERROR: /usr/share/ultimate_edition/${PACKAGE}.tar.gz not found."
			exit 1;
		fi
	fi
	#DONORS LIST

	if ! [[ -f "${DONORS}" ]]; then
		Center "Pulling donors list..."
		#Download "http://os-builder.com/$DONORS"
		if ! [[ -f "${DONORS}" ]]; then
			if [[ -f "/usr/share/ultimate_edition/donors.csv" ]]; then
				Encapsulate "Donors list is not on the server, pulling local copy:"
				cp "/usr/share/ultimate_edition/${DONORS}" .
				if [[ -f "$DONORS" ]]; then
					Encapsulate "Success."
				else
					Error "CRITICAL ERROR: ${DONORS} not found."
				fi
			else
				Error "CRITICAL ERROR: /usr/share/ultimate_edition/${DONORS} not found."
				exit 1;
			fi
		else
			Encapsulate "Donors list exists, continuing."
		fi
	else
		Encapsulate "Donors list exists, continuing."
	fi

	FullBar
	FOLDER="${PACKAGE}"
	FTP="${FOLDER}/usr/share/ubiquity-slideshow/slides/"

	if [[ -d "${FTP}" ]]; then
		cd "${FTP}" || exit 1;
	else
		Error "Critical Error: No ${FTP} folder.  We are in ${PWD}."
		exit 1;
	fi

	Center "Processing donors list:"
	FullBar
	#Drop the header
	echo '<div class="header"><h1 class="title">Donors</h1></div>

<div class="main">

<div class="content wrap-top">
<p>We have recently began asking for <a href="http://ultimateedition.info/donations/">donations</a>.&nbsp; The below people are the ones responsible for keeping #DISTRO a float. Thanks,</p>
<b>Donors</b> (in chronological order):<br>
<center>
<table id="wp-table-reloaded-id-1-no-1" border="1">
<tbody>' > donors.html
	#Process list of donors written in comma seperated value.
	if [[ -d "${EXEC}" ]]; then
		cd "${EXEC}" || exit 1;
	else
		Error "Critical Error: No ${EXEC} folder."
		exit 1;
	fi
	#cat "$DONORS" | while read LINE
	#do
	while read -r LINE
	do
    	DDON=$(echo "${LINE}" | cut -d"," -f1)
		DNAME=$(echo "${LINE}" | cut -d"," -f2| sed 's/\"//g')
		DAMOUNT=$(echo "${LINE}" | cut -d"," -f4)
		echo "<tr><td>${DDON}</td><td>${DNAME}</td><td>${DAMOUNT}</td></tr>" >> ${FTP}/donors.html
		if [[ "$NDONORS" -ge 1 ]]; then
			DNAME=$(echo "${DNAME}" | sed "s/<.*//g" | sed 's/ /_/g')
			Columnize "${NDONORS}" "${DDON}" "${DNAME}" "${DAMOUNT}"
		else
			Columnize
			FullBar
		fi
		NDONORS=$((NDONORS + 1))
	done < "${DONORS}"

	if [[ -d "${FTP}" ]]; then
		cd "${FTP}" || exit 1;
	else
		Error "Critical Error: No ${FTP} folder. We are in ${PWD}"
		exit 1;
	fi
	#close out the html
	echo '</tbody>
</table>
</center></p>
</div>
<img class="icon" src="icons/ubuntu-logo.png" alt="" />' >> donors.html

	if [[ -d "${EXEC}" ]]; then
		cd "${EXEC}" || exit 1;
	else
		Error "Critical Error: No ${EXEC} folder. We are in ${PWD}"
		exit 1;
	fi

	Center "Processing ${PACKAGE}"
	if [[ -d "${FTP}" ]]; then
		cd "${FTP}" || exit 1;
	else
		Error "Critical Error: No ${FTP} folder. We are in ${PWD}"
		exit 1;
	fi
	shopt -s nullglob
	declare -i INDEX;
	declare -a HTML=();
	declare -a SCAN=('#DISTRO' '#VERSION' '#ISLTS' '#TYPE');
    if [[ -n "${LTS}" ]]; then
        if [[ "$DEBUG" ]]; then
            echo "Setting LTS in html, LTS: ${LTS}"
        fi
    	declare -a REPLACEMENT=("Ultimate Edition" "${CVERSION}" "LTS (Long Term Supported)" "${DTYPE^}");
    else
        if [[ "$DEBUG" ]]; then
            echo "Setting NON LTS in html, LTS: ${LTS}"
        fi
        declare -a REPLACEMENT=("Ultimate Edition" "${CVERSION}" "" "${DTYPE^}");
    fi
	HTML=(./*.html)
	for I in "${HTML[@]}"
	do
		INDEX=0
		for EACH in "${SCAN[@]}"
		do
			Encapsulate "Processing html file: ${I}"
			sed -i "s/${EACH}/${REPLACEMENT[$INDEX]}/g" "${I}"
			if [[ "$DEBUG" ]]; then
				Encapsulate "Looking for ${EACH} in $i, Replacing with ${REPLACEMENT[$INDEX]}"
			fi
			INDEX=$((INDEX+1))
		done
	done

	if [[ -d "${EXEC}" ]]; then
		cd "${EXEC}" || exit 1;
	else
		Error "Critical Error: No ${EXEC} folder."
		exit 1;
	fi

	Encapsulate "Donors list & HTML has been processed, building DEBIAN Package:"
	SUCCESS=$(dpkg --build "${PACKAGE}")
	if [[ -f "${PACKAGE}.deb" ]]; then
		Encapsulate "Success."
	else
		Error "CRITICAL FAILURE: building ${PACKAGE}"
		exit 1;
	fi
	Encapsulate "Cleaning up."
	if [[ -f "donors.csv" ]]; then
		rm "donors.csv"
	fi
	if [[ -d "${PACKAGE}/" ]]; then
		rm -R "${PACKAGE:?/}"
	fi
	Center "Generation of ${PACKAGE}.deb complete."
	Center "Exiting Ultimate Edition usplash builder."
	exit 0;
}

# 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> [TYPE]"
		FullBar
		Encapsulate "Invokes ${PROGNAME} to build Ubiquity splash files for"
		Encapsulate "Ultimate Edition <VERSION> optionally [TYPE] from scratch."
		Encapsulate "The format must comply as follows:"
		Encapsulate "<VERSION> [LITE/GAMERS/SERVER]"
		Encapsulate "Valid arguments are as follows and <REQUIRED>:"
		Encapsulate "Version: 3.4, 3.5 - 5.1"
		Encapsulate "[TYPES]"
		Encapsulate " "
		Encapsulate "Lite, Gamers, Server, and Minimal-server"
		Encapsulate "Lite, gamers, server and DE's as per synopsis is [OPTIONAL]"
		FullBar
		Encapsulate "Example: ${PROGNAME} --build 5.0 lite"
		Encapsulate "Will build Ubiquity Splash files for Ultimate Edition 5.0 Lite"
		FullBar;;
		ALL|v|version)
		Encapsulate ""
		Encapsulate"Usage version;"
		FullBar
		Center "${PROGNAME} -v"
		FullBar
		Encapsulate "Displays ${PROGNAME}'s version number and exits."
		FullBar;;
		ALL|h|help|\?)
		Encapsulate ""
		Encapsulate "Useage Help [COMMAND];"
		FullBar
		Center "${PROGNAME} -h [COMMAND]"
		FullBar
		Encapsulate "Displays this message. For futher information ${PROGNAME} help [COMMAND]"
		Encapsulate "or refer to the manpages."
		Encapsulate "man ${PROGNAME}"
		Encapsulate ""
		Encapsulate "Example: ${PROGNAME} -h version"
		Encapsulate "Will display help about the command version"
	esac
	exit 0
}

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

case "${1}" in
	-h|--help|-\?) Help "$@"; exit 0;;
	-v|--version) VersionDump "$@"; exit 0;;
	-b|--build) BuildUsplash "$@"; 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/
# ==============================================================================
