shopt -s extglob

if [ $(uname) == Darwin ]; then
    sed() { command sed -l "$@"; }
else
    sed() { command sed -u "$@"; }
fi

# Syntax sugar.
indent() {
  sed "s/^/       /"
}

# Clean up pip output
cleanup() {
  sed -e 's/\.\.\.\+/.../g' | sed -e '/already satisfied/Id' | sed -e '/Overwriting/Id' | sed -e '/python executable/Id' | sed -e '/no previously-included files/Id'
}

# Buildpack Steps.
puts-step() {
  echo "-----> $@"
}

# Buildpack Warnings.
puts-warn() {
  echo " !     $@"
}

# Usage: $ set-env key value
set-env() {
  echo "export $1=$2" >> $PROFILE_PATH
}

# Usage: $ set-default-env key value
set-default-env() {
  echo "export $1=\${$1:-$2}" >> $PROFILE_PATH
}

# Usage: $ set-default-env key value
un-set-env() {
  echo "unset $1" >> $PROFILE_PATH
}

# Does some serious copying.
deep-cp() {
  declare source="$1" target="$2"

  mkdir -p "$target"

  # cp doesn't like being called without source params,
  # so make sure they expand to something first.
  # subshell to avoid surprising caller with shopts.
  (
    shopt -s nullglob dotglob
    set -- "$source"/!(tmp|.|..)
    [[ $# == 0 ]] || cp -a "$@" "$target"
  )
}

# Does some serious moving.
deep-mv() {
  deep-cp "$1" "$2"
  deep-rm "$1"
}

# Does some serious deleting.
deep-rm() {
  # subshell to avoid surprising caller with shopts.
  (
    shopt -s dotglob
    rm -rf "$1"/!(tmp|.|..)
  )
}


sub-env() {

  WHITELIST=${2:-''}
  BLACKLIST=${3:-'^(GIT_DIR|PYTHONHOME|PYTHONPATH|LD_LIBRARY_PATH|LIBRARY_PATH|PATH)$'}

  (
    if [ -d "$ENV_DIR" ]; then
      for e in $(ls $ENV_DIR); do
        echo "$e" | grep -E "$WHITELIST" | grep -qvE "$BLACKLIST" &&
        export "$e=$(cat $ENV_DIR/$e)"
        :
      done
    fi

    $1

  )
}
