#!/usr/bin/env bash
# Custom bash settings

# get parent process name
local parent="$(ps -o command= -p "$PPID" | cut -f1 -d' ')"
if [[ "$parent" == *alacritty ]]; then
    export SHLVL=1
    if [[ -z "$TMUX" && -z "$NOTMUX" ]]; then
        if [[ "$PWD" == "$HOME" ]]; then
            exec auto-tmux
        else
            exec auto-tmux -n
        fi
    fi
elif [[ "$parent" == "tmux" ]]; then
    export SHLVL=1
fi
if [[ ! -v TMPDIR ]]; then
    mkdir -p "/tmp/$USER"
    export TMPDIR="/tmp/$USER"
fi

# default prompt command sets window title
unset PROMPT_COMMAND
# save command history to ~/.cache/bash_history, no limit
_load history
# aliases
_load aliases
# set xdg env vars to keep home directory clean
_load xdg
_load func

if _exists fzf; then
    export FZF_DEFAULT_OPTS="--bind=ctrl-u:page-up,ctrl-d:page-down"
    eval "$(fzf --bash)"
fi

# use starship prompt, unless in linux terminal
if [[ "$TERM" != "linux" ]]; then
    [[ -v SSH_CONNECTION ]] && _set_title_suffix="@$(hostname)"
    # suppress setting title for the commands run by nix-shell initalization
    [[ -v IN_NIX_SHELL ]] && _suppress_title=1
    function _set_win_title {
        if [[ -v _suppress_title ]]; then
            # this is the last command run during nix-shell initalization
            if [[ "$@" == "shopt -s execfail" ]]; then
                unset _suppress_title
            fi
            return
        fi
        # check if still in .bashrc
        if declare -F _bashrc_main > /dev/null; then
            return
        elif [[ "$@" != @("starship_precmd"|""|"__fzf_history__"|"fzf-file-widget"|"history -a"|"__zoxide_hook") && ! "$@" =~ _comp.* ]]; then
            printf "\e]0;%s | %s | %s\a" "$(dirs +0)$_set_title_suffix" "$@" "$(date +"%H:%M:%S")"
        fi
    }
    # set window title after running command
    trap "$(trap -p DEBUG | awk -F"'" '{print $2 ";"}')_set_win_title \"\${BASH_COMMAND}\"" DEBUG
    _exists starship && eval "$(starship init bash)"
else
    # [username pwd] green $ reset
    PS1="[\u \W] \[\e[32;1m\]\$\[\e[0m\] "
    # set shell level
    if [[ "$parent" == "login" ]]; then
        export SHLVL=0
    fi
fi
_exists zoxide && eval "$(zoxide init bash)"


# set vi mode
set -o vi
_exists nvim && export EDITOR=nvim || export EDITOR=vim
export BROWSER=librewolf

# disable xon/xoff flow control (ctrl-s, ctrl-q)
stty -ixon
# do not need to use cd to change directories
shopt -s autocd
# do not overwrite files when redirecting
set -o noclobber
# glob hidden files
shopt -s dotglob

# startup script for choosing environment
if [[ -z $DISPLAY && "$(tty)" == "/dev/tty1" ]]; then
    _load startup
fi
