it2_saved_env="$ENV"

_it2_inject() {
    _it2_safe_source() {
        if [[ -f "$1" && -r "$1" ]]; then
            builtin source "$1"
            builtin return 0
        fi
        builtin return 1
    }

    if [[ -n "$IT2_BASH_INJECT" ]]; then
        builtin local it2_bash_inject="$IT2_BASH_INJECT"
        builtin unset IT2_BASH_INJECT ENV
        if [[ -z "$HOME" ]]; then
            HOME=~;
        fi
        if [[ "$it2_bash_inject" == *"posix"* ]]; then
            # Command line was like bash --posix, leave it in posix mode and restore $ENV.
            _it2_safe_source "$IT2_BASH_POSIX_ENV" && builtin export ENV="$IT2_BASH_POSIX_ENV"
        else
            builtin set +o posix
            if [[ -n "$IT2_BASH_UNEXPORT_HISTFILE" ]]; then
                builtin export -n HISTFILE
                builtin unset IT2_BASH_UNEXPORT_HISTFILE
            fi

            # See run_startup_files() in shell.c in the Bash source code
            if builtin shopt -q login_shell; then
                if [[ "$it2_bash_inject" != *"no-profile"* ]]; then
                    _it2_safe_source "/etc/profile"
                    _it2_safe_source "$HOME/.bash_profile" || _it2_safe_source "$HOME/.bash_login" || _it2_safe_source "$HOME/.profile"
                fi
            else
                if [[ "$it2_bash_inject" != *"no-rc"* ]]; then
                    # Linux distros build bash with -DSYS_BASHRC. Unfortunately, there is
                    # no way to to probe bash for it and different distros use different files
                    # Arch, Debian, Ubuntu use /etc/bash.bashrc
                    # Fedora uses /etc/bashrc sourced from ~/.bashrc instead of SYS_BASHRC
                    # Void Linux uses /etc/bash/bashrc
                    _it2_safe_source "/etc/bash.bashrc" || _it2_safe_source "/etc/bash/bashrc"
                    if [[ -z "$IT2_BASH_RCFILE" ]]; then
                        IT2_BASH_RCFILE="$HOME/.bashrc"
                    fi
                    _it2_safe_source "$IT2_BASH_RCFILE"
                fi
            fi
        fi
        builtin unset IT2_BASH_RCFILE IT2_BASH_POSIX_ENV
    fi

    builtin unset -f _it2_safe_source
}

_it2_inject
builtin unset -f _it2_inject

builtin source $(dirname "$it2_saved_env")/iterm2_shell_integration.bash
builtin unset -f it2_saved_env
