#!/usr/bin/bash
#
# Compost: a waf project compositor for the ELT
#
# SPDX-FileCopyrightText: 2026 European Southern Observatory (ESO)
# SPDX-License-Identifier: LGPL-3.0-only
#
PARAMS=$@

# Defined before, so can be overridden in CFG_FILE if desired
EXEC_CMD="waf"

#
# Environment variables:
#
# PREFIX           = composition target
# CFG_FILE         = configuration file to use
#
if [ -z "$CFG_FILE" ]; then
  CFG_FILE="compost.conf"
fi

echo "[Notice] configuration file used $CFG_FILE"

#
# Configuration file variables:
#
# NR               = Number of projects to compose (need to be in order 0 -> ....)
# PROJ_DIR[x]      = Directory to CWD to for project x
# PROJ_<step>[x]   = Parameters for <step> (ie. build, install, test) for project x
# PROJ_DFL_<step>  = Default parameters for <step> (ie. build, install, test) if missing
#
# Configuration files are (executed) shells, so you can include them with ". another.conf"
# or use other variables at your convenience when defining the above ones
#

if [ "$1" == "--info" ]; then
  git submodule foreach git branch -a --contains HEAD
  exit 0
fi

if [ -z "$PREFIX" ]; then
  echo "Error: no PREFIX set, cannot proceed"
  exit -1
fi

# Config will contain all info for projects to iterate, specifically order
if [ -f $CFG_FILE ]; then
  . ${CFG_FILE}
else
  echo "Error: configuration file \"${CFG_FILE}\" missing"
  exit -2
fi

# We want to stop immediately on errors
set -e

# For each project in config
for i in `seq 0 $NR`; do
  ADD_PARAMS=""
  # Go in dir
  pushd ${PROJ_DIR[$i]}
  # Append if needed param for requested step/command
  for cmd in $PARAMS; do
    VAR=PROJ_$cmd[$i]
    if [[ -z ${!VAR} ]]; then VAR=PROJ_DFL_$cmd; fi; # Use default if array entry undefined
    ADD_PARAMS="${!VAR} $ADD_PARAMS"
  done
  # Execute
  echo "Executing $EXEC_CMD ${ADD_PARAMS} ${PARAMS}"
  $EXEC_CMD ${ADD_PARAMS} ${PARAMS}
  popd
done

