#!/bin/bash
# Inpito - Trinity Build Script
# By Jerry Nettrouer II<trinity@inpito.org>

# set -o verbose #echo on
# set +o verbose #echo off

# Unless otherwise indicated install the package
DO_INSTALL=${DO_INSTALL:-YES}
DO_PACKAGE=${DO_PACKAGE:-YES}

# I hate the /usr/local ... I've lost many hours of compiled time to it
PATH=$( echo $PATH | sed -e 's+/usr/local/bin:++g' )
PATH=$( echo $PATH | sed -e 's+/usr/local/sbin:++g' )
MANPATH=$( echo $MANPATH | sed -e 's+/usr/local/man:++g' )

CWD=$( pwd )
COMPLOG="/var/log/compile"

# Automatically determine the architecture we're building on:
if [ -z "$ARCH" ]; then
  case "$( uname -m )" in
    i?86) ARCH=i486 ;;
    arm*) ARCH=arm ;;
    # Unless $ARCH is already set, use uname -m for all other archs:
       *) ARCH=$( uname -m ) ;;
  esac
fi

# if needed make the compile log directory if needed
if [ ! -d $COMPLOG ]; then
	mkdir -p $COMPLOG
fi

# If neeed create a directory for packages
if [ "${DO_PACKAGE}" = "YES" ]; then
	PACKAGETZ=${PACKAGETZ:-"$HOME/$ARCH-packages/"}
	
	# Create a directory for packages
	if [ ! -d $PACKAGETZ ]; then
		mkdir -p $PACKAGETZ
	fi
fi

# The list of programs used in the inpito systems
source $CWD/trinity.programs.sh

for PLS in "${programs_list[@]}"
do

	# Obtian the package name
	NAME=$( echo $PLS | sed -e "s:^.*/::g" )

	# Enter the application directory
	cd $CWD/$PLS

	# Delete any previous compile log
	if [ -f $COMPLOG/$NAME.log ]; then
		rm -f $COMPLOG/$NAME.log
	fi

	# Just to be safe I'm moving lib for every x86_64 program at the moment
	if [ "$ARCH" = "x86_64" ]; then
		mv /usr/lib /usr/zz_lib
	fi

	# Compile the SlackBuild Script and tee output to the screen and a log
	./$NAME.SlackBuild 2>&1 | tee $COMPLOG/$NAME.log

	# Obtian the Package To Install Name
	PTIN=$( cat $COMPLOG/$NAME.log | \
                grep "Slackware package " | \
                grep " created."  | \
                sed -e "s:Slackware package ::g" | \
                sed -e "s: created.::g" )

	# Install the package
	if [ "${DO_INSTALL}" = "YES" ]; then
		echo -en "Installing \033[01;32m$PTIN\033[0m"
		if [ "${DO_PACKAGE}" = "YES" ]; then
			cp $PTIN $PACKAGETZ # Copy the package into the persons home directoy 
		fi
		upgradepkg --reinstall --install-new $PTIN | tee -a $COMPLOG/$NAME.log && sleep 1
	fi

	# Move the lib files back
	if [ "$ARCH" = "x86_64" ]; then
		if [ -d /usr/zz_lib ]; then
			if [ -d /usr/lib ]; then
				echo "$NAME created x86 libraries merging with zz_lib" | tee -a $COMPLOG/$NAME.log
				cd /usr/lib && cp -au * /usr/zz_lib/ && sleep 1
			fi
			echo "Moving the zz_lib diretory back to lib"
			cd /usr && rm -fR /usr/lib && mv /usr/zz_lib/ /usr/lib/
		fi
	fi
done
