#!/bin/bash
#
# Copyright (c) 2019 Clementine Computing LLC.
# 
# This file is part of PopuFare.
# 
# PopuFare is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# PopuFare is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with PopuFare.  If not, see <https://www.gnu.org/licenses/>.
#

modules=`cat client_modules.list | xargs echo`

function copy_to_bin_dir
{
	module_dir_pattern=`for i in $modules; do echo "^\./$i"; done | xargs echo | tr ' ' '|'`
	built_binaries=`find . -name buildit.sh | xargs egrep -o -- "-o[[:space:]]+[^[:space:]]+"  | sed 's/buildit.sh:-o //' | egrep $module_dir_pattern`

	(rm ./bin/$target/*; mkdir -p ./bin/$target/;) 2> /dev/null
	

	for i in $built_binaries; do
		cp $i ./bin/$target/	
	done
}


target=$1
failed_mods=""

. configure_target.sh.include

if [ -z "$target_ok" ]; then
	echo "No rules to build for target \"$target\""
	exit 2
fi

for mod in $modules; do
	if (cd $mod; ./buildit.sh); then
		echo "Module \"$mod\" built successfully for $target"
	else
		echo "Module \"$mod\" failed to build for $target"
		failed_mods="$failed_mods $mod"
	fi
done

if [ -n "$failed_mods" ]; then
	echo
	echo "The following modules failed to build: $failed_mods"
	exit 1
else
	echo
	echo "All modules built!  Attempting to copy to ./bin/$target"
	copy_to_bin_dir
	exit 0
fi
