#!/bin/bash -e

# Includes
PATH="${PATH}:$(dirname $0):/usr/local/share/ui-auto:/usr/share/ui-auto"
. ui-libopt.sh

# Options
ui_opt_init "Wrapper around ui-auto-release to run for multiple projects." "\
Setup cook book:
 (1) On initial setup, run once to get the config dir:
     ui-auto-release-multi -n -s dontcare.
 (2) Add a suite: mkdir CONFFDIR/mysuite.d
 (3) Add a project: touch CONFFDIR/mysuite.d/10_myproject.conf
 (4) Run once again using -n: ui-auto-release-multi -n -s mysuite

The last step will show you what we are actually doing, and what
config files are sourced.  In each sourced file, you may set the
special variables UAR_ARGS_ALL and UAR_ARGS -- both will be used
as arguments for the ui-auto-release call. Use UAR_ARGS_ALL in
global or per-suite config file, and set UAR_ARGS to special
project valuse in project config files. Continue configuring
your suite and check by running with -n until satisfied."

ui_opt_add "c:" "Config directory." "${HOME}/.ui-auto-release-multi"
ui_opt_add "s:" "Select series to run."
ui_opt_add "n"  "Don't actually run ui-auto-release, just show what we would do."
ui_opt_parse "$@"

setDefault()
{
	[ -n "${!1}" ] || eval "export ${1}=\"${2}\""
}

source_conf()
{
	local conf="${1}"
	if [ -e "${conf}" ]; then
		echo "Sourcing conf: \"${conf}\""
		. "${conf}"
	else
		echo "Skipping conf: \"${conf}\""
	fi
}

SUITEDIR="$(ui_opt_get c)/$(ui_opt_get s).d"

setDefault CFLAGS "-g -O0 -Wall"
setDefault CXXFLAGS "-g -O0 -Wall"

# Create and enter rundir
mkdir -p -v "$(ui_opt_get c)/rundir"
cd "$(ui_opt_get c)/rundir"

# Source global and suite conf
source_conf "$(ui_opt_get c)/conf"
source_conf "${SUITEDIR}/conf"

# Run projects in suite
FAILED=()
OK=()
for f in $(find "${SUITEDIR}/" -name "*.conf" | sort); do
	PJ="$(basename "${f}" .conf)"
	echo "----------------------------------------------------------------"
	echo "Running $(basename "${SUITEDIR}")(${PJ}):"
	echo "----------------------------------------------------------------"
	# Subshell -- don't taint any variables here
	(
		# Source project conf
		source_conf "${f}"

		# Run ui-auto-release
		CMD="ui-auto-release ${UAR_ARGS_ALL} ${UAR_ARGS}"
		echo "Running: \"${CMD}\""
		ui_opt_given n || ${CMD}
	)
	if [ $? -ne 0 ]; then
		FAILED[${#FAILED[@]}]="${PJ}"
	else
		OK[${#OK[@]}]="${PJ}"
	fi
done

echo "================================================================"
echo "OK: ${#OK[*]} project(s): ${OK[*]}" >&2
if [ ${#FAILED[@]} -ne 0 ]; then
	echo "*FAILED*: ${#FAILED[*]} project(s): ${FAILED[*]}" >&2
	exit 1
fi
exit 0
