#!/bin/bash
#
# install-drupal
#
# Prepare a Drupal site to run the behat tests on.
#
SELF_DIRNAME="`dirname -- "$0"`"
source $SELF_DIRNAME/setup-environment

# Set up our Drush alias, and do any custom pre-install tasks.
source $SELF_DIRNAME/prepare-to-install
aborterr "Prepare-to-install script failed."

# Set up some variables to match the environment
FALLBACK_DBURL=mysql://root@localhost/drupal
SITENAME_SUFFIX=" Local CI Test Site"
if [ -n "$TRAVIS" ]
then
  SITENAME_SUFFIX=" Travis CI Test Site"
fi
if [ -n "$CIRCLECI" ]
then
  FALLBACK_DBURL=mysql://ubuntu@127.0.0.1/circle_test
  SITENAME_SUFFIX=" Circle CI Test Site"
fi

# Use Drush to install Drupal
cd "$DRUPAL_ROOT"
echo drush site-install -y "${PROFILE:-${DEFAULT_PROFILE:-standard}}" --sites-subdir="$TESTSITEDIR" --site-name="${SITE_NAME:-${DEFAULT_SITE_NAME}}$SITENAME_SUFFIX" --db-url="${DBURL:-${DEFAULT_DBURL:-${FALLBACK_DBURL}}}" --account-name=${ACCOUNT:-${DEFAULT_ACCOUNT:-admin}} --account-pass=${PASSWORD:-${DEFAULT_PASSWORD:-admin}}
drush site-install -y "${PROFILE:-${DEFAULT_PROFILE:-standard}}" --sites-subdir="$TESTSITEDIR" --site-name="${SITE_NAME:-${DEFAULT_SITE_NAME}}$SITENAME_SUFFIX" --db-url="${DBURL:-${DEFAULT_DBURL:-${FALLBACK_DBURL}}}" --account-name=${ACCOUNT:-${DEFAULT_ACCOUNT:-admin}} --account-pass=${PASSWORD:-${DEFAULT_PASSWORD:-admin}}
if [ $? != 0 ]
then
  echo "Could not install Drupal" >&2
  exit 1
fi

# Add in include of settings.local.php to the settings.php file.
chmod +w "$DRUPAL_ROOT/sites/$TESTSITEDIR"
chmod +w "$DRUPAL_ROOT/sites/$TESTSITEDIR/settings.php"
echo  "test settings.php is $DRUPAL_ROOT/sites/$TESTSITEDIR/settings.php"
grep -q 'settings.local.php' "$DRUPAL_ROOT/sites/$TESTSITEDIR/settings.php"
if [ $? != 0 ]
then
  cat << __EOF__ >> "$DRUPAL_ROOT/sites/$TESTSITEDIR/settings.php"
\$local_settings = __DIR__ . "/settings.local.php";
if (is_file(\$local_settings)) {
  include "\$local_settings";
}
__EOF__
fi

# If there is a local script 'post-install', then run it.
POST_INSTALL="$PROJECT_BASE_DIR/scripts/post-install"
if [ -f "$POST_INSTALL" ]
then
  cd "$DRUPAL_ROOT"
  echo "$POST_INSTALL" "$LOCAL_DRUSH_ALIAS"
  "$POST_INSTALL" "$LOCAL_DRUSH_ALIAS"
  aborterr "Post-install script failed"
fi

# Deprecated: also run install-configuration (the old name for post-install).
INSTALL_CONFIGURATION="$PROJECT_BASE_DIR/scripts/install-configuration"
if [ -f "$INSTALL_CONFIGURATION" ]
then
  cd "$DRUPAL_ROOT"
  echo "$INSTALL_CONFIGURATION" "$LOCAL_DRUSH_ALIAS"
  "$INSTALL_CONFIGURATION" "$LOCAL_DRUSH_ALIAS"
  aborterr "Install-configuration script failed."
fi
