#!/usr/bin/env bash

## Description: ddev poser, plus the optional local-only packages in composer.local.json.
## Usage: poser-local [flags] [args]
## Example: "ddev poser-local" or "ddev poser-local --prefer-source"
## ExecRaw: true
## MutagenSync: true

# NOT #ddev-generated: this is ours. `ddev poser` (from the ddev-drupal-contrib
# add-on) installs exactly what composer.json declares, which is what CI does and
# what the module contract promises. Use this instead when you want extra
# packages present in YOUR checkout only — an AI provider stack, a workflow
# engine to compare against, whatever — without putting them in composer.json.
#
# composer.local.json is gitignored. See composer.local.json.example.

set -eu -o pipefail

export COMPOSER=composer.contrib.json
.ddev/commands/web/expand-composer-json

if [[ -f composer.local.json ]]; then
  # Objects merge recursively (`*`), so require/require-dev/config/extra layer on
  # top of the generated file. `repositories` is an array, which `*` would
  # replace outright, so concatenate it by hand with the local entries first —
  # earlier repositories win in Composer.
  jq -s '
    (.[0].repositories // []) as $generated
    | (.[1].repositories // []) as $local
    | (.[0] * .[1])
    | .repositories = ($local + $generated)
    | del(._comment)
  ' composer.contrib.json composer.local.json > composer.contrib.json.merged
  mv composer.contrib.json.merged composer.contrib.json
  echo "poser-local: merged composer.local.json into the generated composer.contrib.json"
else
  echo "poser-local: no composer.local.json found — this is a plain 'ddev poser' run."
fi

composer install "$@"
# The -f flag suppresses errors if lock file does not exist.
rm -f composer.contrib.json composer.contrib.lock
touch $DDEV_DOCROOT/core/.env
