#!/bin/bash
# ~/.envrcd/.envrcd: this file should be symlinked to ~/.bashrc

# if not running interactively, don't do anything
case $- in
    *i*) ;;
      *) return;;
esac

ENVRCD_NAME="envrcd"
ENVRCD_PATH="${HOME}/.${ENVRCD_NAME}"

if [ ${ENVRCD_SET_NOENVRCD} ]; then
    return
fi

if [ ${ENVRCD_SET_DEBUG} ]; then
    ENVRCD_DEBUG="true"
fi

# prints messages when in debug mode
function debug {
    if [ ${ENVRCD_DEBUG} ]; then
        echo "${ENVRCD_NAME}: ${@}"
    fi
}

# source files from multiple arguments with shell globbing
function source_if_exists {
    for argument in "${@}"; do
        local expanded_argument="${argument/#\~/${HOME}}"
        for f in ${expanded_argument}; do
            if [[ -f "${f}" ]]; then
                debug "sourcing ${f}"
                source "${f}"
            fi
        done
    done
}

# source common files from a profile (${ENVRCD_NAME}, ${ENVRCD_NAME}.d, .bashrc)
function source_profile_if_exists {
    source_if_exists "${ENVRCD_PATH}/profile/${1}/${ENVRCD_NAME}"
    source_if_exists "${ENVRCD_PATH}/profile/${1}/${ENVRCD_NAME}.d/*"
    source_if_exists "${ENVRCD_PATH}/profile/${1}/.bashrc"
}

# source envrcd code
source_if_exists "${ENVRCD_PATH}/${ENVRCD_NAME}.d/*"