#!/usr/bin/env bash
shopt -s extglob
shopt -s nullglob

set -e

### Path resolving from drush/drush:drush

# Get the absolute path of this executable
SELF_DIRNAME=$(dirname -- $0)
SELF_PATH=$(cd -P -- "$SELF_DIRNAME" && pwd -P)/$(basename -- $0)

# Resolve symlinks - this is the equivalent of "readlink -f", but also works with non-standard OS X readlink.
while [ -h "$SELF_PATH" ]; do
    # 1) cd to directory of the symlink
    # 2) cd to the directory of where the symlink points
    # 3) Get the pwd
    # 4) Append the basename
    DIR=$(dirname -- "$SELF_PATH")
    SYM=$(readlink "$SELF_PATH")
    SYM_DIRNAME=$(dirname -- "$SYM")
    SELF_PATH=$(cd "$DIR" && cd "$SYM_DIRNAME" && pwd -P)/$(basename -- "$SYM")
done

# Build the path to our script dir.
export DCIR_SCRIPT_DIR=$(dirname "$SELF_PATH")

# Parse YAML configuration file. 
CONFIG_FILE="/dcir/.dcir.yml"
if [ -f $CONFIG_FILE ]; then
    . $DCIR_SCRIPT_DIR/utility/parse_yaml.sh
    eval $(parse_yaml $CONFIG_FILE config_)

# Auto-magically discover configuration if possible.
else
    FILES=/dcir/*.info?(.yml)
    if [ ${#FILES[@]} -eq 1 ] && [ ! -z ${FILES[0]} ]; then
        CONFIG_DRUPAL_CORE=$(grep 'core.*[0-9]' < ${FILES[0]} | grep -o '[0-9]*')
        FILENAME=$(basename ${FILES[0]})
        CONFIG_DRUPAL_PROJECT=${FILENAME%.info?(.yml)}

    # Error: No config could be determined.
    else
        echo "Error: .dcir.yml file not found." 1>&2
        exit 1
    fi
fi

# Initialise environment.
SCRIPT="$DCIR_SCRIPT_DIR/environments/drupal-${CONFIG_DRUPAL_CORE:-8}.sh"
if [ -r "$SCRIPT" ]; then
    . "$SCRIPT"
fi
cd drupal-${CONFIG_DRUPAL_CORE:-8}

# Include project specific functions/variables.
SCRIPT="$DCIR_SCRIPT_DIR/projects/${CONFIG_DRUPAL_PROJECT_TYPE:-module}.sh"
if [ -r "$SCRIPT" ]; then
    . "$SCRIPT"
fi

# Symlink project into relevant destination path.
ln -s /dcir $DRUPAL_PROJECT_DIR/$CONFIG_DRUPAL_PROJECT

# Initialise project.
drupal_project_init

# Run Drush webserver.
drush runserver "http://127.0.0.1:8080" > /dev/null 2>&1 &

# Include and execute runners.
for SCRIPT in "$DCIR_SCRIPT_DIR/runners"/*.sh; do
    if [ -r "$SCRIPT" ]; then
        . "$SCRIPT"
    fi
done