# Sourced by the scripts of the ecosystem, never run. read_rc runs the commands of the files that exist, to set the environment of the
# tools once (PATH, which php...): the accounts of the machine (/etc/w4os/database.rc and database-admin.rc), the .env of the
# project given, then ~/.opensimrc (or the file OPENSIM_RC names). They are bash files,
# what they say is executed as it is, e.g. in ~/.opensimrc:
#
#   export PATH="$(echo "$PATH" | sed "s#:[^:]*/lerd/[^:]*:#:#"):/opt/magic/bin"

#
# What the run was given wins over the files: a variable of the suite typed before the command, or exported in its shell
# (OPENSIM_DB_USER=other opensim ...). The first reader of a run says which these are (W4OS_RC_GIVEN, kept through sudo); the
# readers after it (the commands it starts) keep those, and read every other one from the files again, which a step of the run
# may have written since. The PATH is the files' business: never kept.

# read_rc [PROJECT_DIR]
read_rc() {
    local file name kept=()
    # The accounts of the machine first (the database user of its grids and the DB admin user, both for the account of the
    # instances), then the project's, then the person's own, which wins
    local machine=${W4OS_MACHINE_RC_DIR:-/etc/w4os}
    if [[ -z "${W4OS_RC_GIVEN+set}" ]]; then
        W4OS_RC_GIVEN=$(compgen -e | { grep -E '^(OPENSIM_|DEFAULT_OWNER_|DOTNET_|CONTAINER_CONNECTION$)' || true; } | tr '\n' ' ')
        export W4OS_RC_GIVEN
    fi
    for name in $W4OS_RC_GIVEN; do
        [[ -z "${!name+set}" ]] || kept+=("$name=${!name}")
    done
    for file in "$machine/database.rc" "$machine/database-admin.rc" "${1:+$1/.env}" "${OPENSIM_RC:-${HOME:-}/.opensimrc}"; do
        # shellcheck disable=SC1090
        [[ -n "$file" && -r "$file" ]] && source "$file"
    done
    for name in ${kept[@]+"${kept[@]}"}; do
        export "$name"
    done
    return 0
}
