#!/bin/bash
# ~/.bashrc is run by bash when an interactive shell which is not a login shell is started
# note: login shells run ~/.bash_profile or ~/.profile instead of ~/.bashrc
# by Ian Kluft

# Source global definitions first so we can override them
if [ -f /etc/bashrc ]; then
	source /etc/bashrc
fi

# get common functions used by both .bashrc and .profile
common_sh="$HOME/.config/sh/common.sh"
if [ ! -e "${common_sh}" ]
then
    echo ".bashrc aborting due to incomplete installation: ~/.config/sh/common.sh not found" >&2
    return 1 # do not use exit here because it will exit the shell, including login shells
fi
# shellcheck source-path=~/.config/sh disable=SC1090,SC1091
source "${common_sh}"

# point BASHRC_DIR at .config/sh/bashrc.d
# (following XDG Base Directory Specification to declutter home dot-files)
BASHRC_DIR="${SH_CONFIG_DIR}/bashrc.d"
export BASHRC_DIR

# make sure BASHRC_DIR existS
if [ ! -d "$BASHRC_DIR" ]
then
    mkdir -p "$BASHRC_DIR"
    chmod u=rwx,go= "$BASHRC_DIR"
fi

# run sh commands from .config/sh/bashrc.d
for file in "${BASHRC_DIR}"/*
do
    case "$file" in

        # shell and bash scripts
        *.sh|*.bash)
            [ -e "$file" ] || continue # catch unmatched globs which are sent verbatim
            # shellcheck disable=SC1090
            source "$file"
        ;;

        # *.import files are text lists of script names to import/run from .config/sh/profile.d
        # the suffix allows multiple import lists, such as one from the git source and a local one for personal scripts
        *.import)
            # shellcheck disable=SC2013,SC2162
            for import in $(sed 's/\s*#.*//' "$file" | grep -v '^\s*$')
            do
                if [ -e "${SH_PROFILE_DIR}/$import" ]
                then
                    # shellcheck disable=SC1090
                    source "${SH_PROFILE_DIR}/$import"
                else
                    echo "warning: '$import' referenced in $file but not found in ${SH_PROFILE_DIR}" >&2
                fi
            done
        ;;
    esac
done

# clean up variables no longer needed after running bashrc.d scripts
if [ -z "${in_dot_profile}" ]
then
    # only clean up source_once() variables if we were not called from .profile, otherwise it also needs them
    cleanup_from_source_once
fi
unset BASHRC_DIR
