#!/bin/bash

#
# This script is called automatically on every `composer update`.
# See "post-update-cmd" in the "scripts" section of composer.json.
#
# This script will create a derived composer.json / composer.lock
# pair for every test scenario.  Test scenarios are defined in the
# "scenarios" file, which should be customized to suit the needs
# of the project.
#

SELF_DIRNAME="`dirname -- "$0"`"
source ${SELF_DIRNAME}/scenarios

echo
echo "::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
echo "::"
echo ":: Update dependencies for the following scenarios:"
echo "::"
echo "::    ${SCENARIOS}"
echo "::"
echo "::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
echo

set -ex

for SCENARIO in ${SCENARIOS} ; do

  dir=dependencies/${SCENARIO}

  # Define indirect variable names
  stability_variable="stability_${SCENARIO}"
  requirement_variable="requirement_${SCENARIO}"
  platform_php_variable="platform_php_${SCENARIO}"

  echo "### Create $dir/composer.json for ${SCENARIO} scenario"
  mkdir -p $dir
  cp composer.json $dir

  # Then set our own platform php version if applicable (otherwise unset it)
  composer -n --working-dir=$dir config platform.php "${!platform_php_variable---unset}"

  # Temporarily set our vendor directory to 'vendor'
  composer -n --working-dir=$dir config vendor-dir vendor

  # Set an appropriate minimum stability for this version of Symfony
  composer -n --working-dir=$dir config minimum-stability "${!stability_variable-stable}"

  # Add a constraint to limit the Symfony version
  composer -n --working-dir=$dir require --dev --no-update "${!requirement_variable}"

  # Create the composer.lock file. Ignore the vendor directory created.
  composer -n --working-dir=$dir update --no-scripts

  # Set the vendor directory to its final desired location.
  composer -n --working-dir=$dir config vendor-dir '../../vendor'

  # The 'autoload' section specifies directory paths that are relative
  # to the composer.json file. We will drop in some symlinks so that
  # these paths will resolve as if the composer.json were in the root.
  for target in $AUTOLOAD_DIRECTORIES ; do
    ln -s -f ../../$target $dir
  done

done
