#!/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_RPM[x]      = Name of RPM package that overrides this entry (if absent, no override)
#                    Only if exact same version found as RPM, will then skip step
# 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
  # Check for RPM override
  if [[ -n "${PROJ_RPM[$i]}" ]]; then
    VER_PROJ=`sed -n "s/.*version=['\"]\(.*\)['\"].*/\1/p" wscript`  # If version is not found becomes ""
    set +e # rpm fails if package not there, so temporarily disable errors
    VER_RPM=`rpm -q --queryformat='%{version}' ${PROJ_RPM[$i]}` # If not there, will have a string telling so
    set -e
    if [[ "$VER_PROJ" == "$VER_RPM" ]]; then # If we'd like to have also >= etc we may use sort -VC or so
      echo "RPM ${PROJ_RPM[$i]} version $VER_RPM found for ${PROJ_DIR[$i]} $VER_PROJ, skipping..."
      popd; continue
    fi
  fi;
  # Execute
  echo "Executing $EXEC_CMD ${ADD_PARAMS} ${PARAMS}"
  $EXEC_CMD ${ADD_PARAMS} ${PARAMS}
  popd
done

