#!/usr/bin/env bash

## Description: Build a bilingual demo site for Entity Change Default Language
## Usage: setup-demo [flags]
## Example: "ddev setup-demo" or "ddev setup-demo --locale=en"

set -eu -o pipefail

# Reinstalling drops every table first, so a second run rebuilds the site
# instead of failing on content that already exists. The admin password is
# random and never printed: sign in with "ddev drush uli".
ADMIN_PASSWORD="$(openssl rand -hex 16)"
drush site:install standard \
  --site-name="Entity Change Default Language" \
  --account-name=admin \
  --account-pass="${ADMIN_PASSWORD}" \
  --yes "$@"

# Drupal only discovers the modules under tests/ when this setting is on.
SETTINGS="${DDEV_DOCROOT}/sites/default/settings.php"
if ! grep -q extension_discovery_scan_tests "${SETTINGS}"; then
  chmod u+w "$(dirname "${SETTINGS}")" "${SETTINGS}"
  cat >> "${SETTINGS}" <<'PHP'

// Discover the demo module under tests/modules.
$settings['extension_discovery_scan_tests'] = TRUE;
PHP
fi
drush cache:rebuild

# The recipe installs the test module, imports its demo configuration
# (Spanish, a translatable article and a reference field) and the content.
drush recipe "${DDEV_APPROOT}/tests/recipes/entity_change_default_language_demo"
drush cache:rebuild

echo "Site ready at ${DDEV_PRIMARY_URL}"
echo "Sign in with: ddev drush uli"
echo "Try: ddev drush ecdl:cdl node 1 es --preserve-languages=en,es"
