#!/bin/bash
# Build ARCH SMP
# Pull in common software
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."
	exit 0;
fi
BuildArchSMP (){
	BASECORES=0
	BASECORE=$(echo "$@" | grep -i "BASECORE")
	if [[ "${BASECORE}" ]]; then
		BASECORES=1
	fi
	# Snatch the number of CPU Core(s) / threads the end user has.
	CORES=$(grep -i "processor" "/proc/cpuinfo" | sed '/model/d' | wc -l)
	(( ACTUALCORES = ${CORES} -1 ))
	FullBar
	Encapsulate "Number of CPU Core(s) / threads(s) detected: ${CORES}"
	Encapsulate "Launching ${CORES} threads to accelerate the building process, please wait."
	#CORES=$(("${CORES}" +3))
	CONTAINS=$(echo "$@" | grep -i 'threads')
	if [[ "${CONTAINS}" ]]; then
		THREADS=$(echo "$@" | grep -i "threads=" | sed "s/^.*threads=//g" | cut -d" " -f1)
		Encapsulate "Threads Specified as: ${THREADS}"
		CALCULATE=$(( "${THREADS}" + 3 + "${BASECORES}" ))
		CORES="${CALCULATE}"
	fi
	shopt -s dotglob
	shopt -s nullglob
	FOLDERS=(*/)
	ARCHPACKAGE=();
	DEBPACKAGE=();
	declare -i INDEX;
	declare -i AINDEX;
	DELETEELEMENT=(".debs/")
	FOLDERS=( "${FOLDERS[@]/$DELETEELEMENT}" ) #Quotes when working with strings
	DELETEELEMENT=("partial/")
	FOLDERS=( "${FOLDERS[@]/$DELETEELEMENT}" )
	DELETEELEMENT=(".arch/")
	FOLDERS=( "${FOLDERS[@]/$DELETEELEMENT}" )
	INDEX=0
	AINDEX=0
	INSTANCE=1
	RUNNINGINSTANCES=$(ps -C repostorm | wc -l)
	for EACH in "${FOLDERS[@]}"
	do
		if [[ -d "${EACH}" ]]; then
			if [[ -f "${EACH}/.PKGINFO" ]]; then
				AINDEX=$(( AINDEX + 1 ))
				ARCHPACKAGE[${AINDEX}]+="${EACH}"
				RUNNINGINSTANCES=$(ps -C repostorm | wc -l)
				# EXPELL all cores, let's go to work, if we have maxed out, wait for one core to finish.
				while [[ "${RUNNINGINSTANCES}" -ge "${CORES}" ]] ;
				do
					RUNNINGINSTANCES=$(ps -C repostorm | wc -l)
				done
			fi
			# Yee HAW we have an open core, let's put it to work.
			if [[ "${RUNNINGINSTANCES}" -lt "${CORES}" ]]; then
				INSTANCE=$(( "${RUNNINGINSTANCES}" + 1 ))
				Encapsulate "Launching thread #${INSTANCE}: Building: ${ARCHPACKAGE[${AINDEX}]} (RUNNING INSTANCES: ${RUNNINGINSTANCES} Internal processes: 2)"
				#INSTANCE=$(( INSTANCE + 1 ))
				sudo repostorm --build "${ARCHPACKAGE[${AINDEX}]}" -YES --suppress & #& allows that to process and continue running through current software hence why the not equal 3 below
			fi
		fi
	done
	TCORES=$(( 3 + "${BASECORES}"))
	while [[ "${RUNNINGINSTANCES}" -ne "1" ]] ;
	do
		#Encapsulate "Waiting for threads to complete: ${RUNNINGINSTANCES}"
		RUNNINGINSTANCES=$(ps -C repostorm | wc -l)
		Spinner "INSTANCES: ${RUNNINGINSTANCES} | TCORES: ${TCORES}"
	done
}
BuildArchSMP
