#!/bin/sh
# ~/.profile is run by bourne-compatible shells when started as login shells
# bash does not run ~/.profile if ~/.bash_profile exists. This .profile is made for both bash/sh.
# note: for interactive non-login shells, bash runs ~/.bashrc instead
# by Ian Kluft

# get common functions used by both .bashrc and .profile
common_sh="$HOME/.config/sh/common.sh"
if [ ! -e "${common_sh}" ]
then
    echo ".profile 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
. "${common_sh}"

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

# if running bash, run bashrc as well as bash scripts in SH_PROFILE_DIR
# shellcheck disable=SC2034
in_dot_profile=1
if [ -n "${BASH_VERSION}" ]
then
    # include .bashrc if it exists
    if [ -f "${HOME}"/.bashrc ]
    then
        if [ -f "${HOME}"/.bashrc ]
        then
            # shellcheck source=~/.bashrc disable=SC1090,SC3046
            source "${HOME}"/.bashrc
        fi
    fi
fi

# run sh commands from .config/sh/profile.d
for file in "$SH_PROFILE_DIR"/*
do
    case "$file" in

        # run POSIX/Bourne shell scripts from .config/sh/profile.d
        "*.sh")
            # shellcheck source-path=~/.config/sh/profile.d disable=SC1090
            . "$file"
        ;;

        # run Bash commands from .config/sh/profile.d
        "*.bash")
            if [ -n "${BASH_VERSION}" ]
            then
                # shellcheck source-path=~/.config/sh/profile.d disable=SC1090,SC3046
                source "$file"
            fi
        ;;

        *)
            # others ignored
        ;;
    esac
done

# clean up variables no longer needed after running profile.d scripts
cleanup_from_source_once
unset PATHFILTER in_dot_profile
