#!/bin/bash
# .bashrc
#
# [2024-05-04]
# Written by Peter Marinov, this is public domain
#
# To activate, ensure `source ~/.bashrc` in .profile OR .bash_profile

# check1: Shell is non-interactive?
[[ $- != *i* ]] && return

# check2: If not running interactively, don't do anything
[[ -z "$PS1" ]] && return

bashrc_v="2024-05-04"
red="\033[0;31m"
RED="\033[1;31m"
blue="\033[0;34m"
BLUE="\033[1;34m"
cyan="\033[0;36m"
CYAN="\033[1;36m"
NC="\033[0m"

if [[ "${TERM}" == "dumb" ]]; then
  echo ".bashrc: dumb terminal (inside emacs?)"
  red=""
  RED=""
  blue=""
  BLUE=""
  cyan=""
  CYAN=""
  NC=""
  # eliminate "bind: warning: line editing not enabled"
  alias bind=true
fi

# Add options for improved verbosity of commands
alias path='echo -e ${PATH//:/\\n}'
alias df='df -kTh'
alias du='du -kh'
the_os=$("uname")
if [[ "${the_os}" == "Darwin" || "${the_os}" == "FreeBSD" ]]; then
  alias ls="ls -F -h -G"
elif [[ "${the_os}" == "NetBSD" ]]; then
  # No colors on NetBSD
  alias ls="ls -F -h"
else
  alias ls="ls -F -h --color=auto"
fi

# Alias some commands to be verbose by default
alias mv='mv -v'
alias rm='rm -v'
alias chmod='chmod -v'

#
# Functions to print and parse timestamps
#
# Pipe to this for color display of timestamp
# Example: echo 2024-05-02T11:37:15-07:00 | timestamp_color
timestamp_color() {
  # If stdout is not a terminal, do nothing
  [[ ! -t 1 ]] && cat && return

  # Split timestamp in 3:
  # 1: 2024-05-02
  # T
  # 2: 11:37:15
  # 3: -07:00
  # Use color for T and for the timezone, restore no-color at the end
  sed -E -e "s/(....-..-..)T(..:..:..)(.*)/\1[0;37mT[0m\2[0;37m\3[0m/"
}

# Parse a timestamp OR display the UNIX timestamp of current time
timestamp() {
  # Hint: To display in another time zone do:
  # TZ=America/New_York date -Iseconds -d @1533415339

  if [[ -z $1 ]]; then
    if [[ "${the_os}" == "Darwin" || "${the_os}" == "FreeBSD" ]]; then
      date +%s
    fi
  else
    if [[ "${the_os}" == "Darwin" || "${the_os}" == "FreeBSD" ]]; then
      date -Iseconds -r $1 | timestamp_color
      return 0
    else
      # date -d "@${1}" '+%Y-%m-%d, %h:%m.%s (%z)'
      date -Iseconds -d "@${1}" | timestamp_color
    fi
  fi
}

# enable color grep if color is supported
MY_GREP_OPTIONS=""
(echo chk | grep --color=auto chk &>/dev/null) && alias grep="grep --color=auto" && MY_GREP_OPTIONS="--color=auto"

#
# Setup prompt
#
# - Detect root => red prompt
# - Detect ssh => prefix user name with "ssh:"
# - Detect screen => prefix the prompt with "[s]"
# - Show exit code of last command + time elapsed since last prompt
#   (Use pale color when exit code was 0, and bold for non-0)
set_prompt() {
  # Exit code of command is passed
  local _result=$1
  local _elapsed_seconds=$2

  local _co_yellow='\[\033[33m'
  local _co_restore='\[\033[0m'

  if [[ "${TERM}" == "dumb" ]]; then
    # Shell inside dumb terminal (emacs): remove prompt colors
    PS1="{\\u@\\h \\w}\n${_id} "
    return
  fi

  if [[ "$1" == "0" ]]; then
    # White (light gray)
    local _co_result='\[\033[37m'
  else
    # Cyan
    local _co_result='\[\033[36m'
  fi

  local _git='$(parse_git_branch)'

  local _screen=''
  if [[ "${TERM}" == "screen" || "${TERM}" == "screen.xterm-256color" ]]; then
    _screen='{s${WINDOW}} '
  fi

  local _co_user=''
  local _char_prompt='?'
  if [[ "$UID" == "0" ]]; then
    # Make root prompt to be red
    _co_user='\[\033m\033[31m\]'
    _char_prompt='#'
  else
    # Green
    _co_user='\[\033m\033[32m\]'
    _char_prompt='$'
  fi

  export PS1="${_co_user}${_screen}\u@\h${PROMPT_C1} ${_co_yellow}\w ${_git} ${_co_result}${_result}, ${_elapsed_seconds}${_co_restore}\n${_char_prompt} "

  export PS2='> '
}

# First set of prompt, setting continuosly from $PROMPT_COMMAND
set_prompt 0 0

#
# Print execution time of commands
# Based on ideas from: https://github.com/jichu4n/bash-command-timer
_at_prompt=1
_command_start_time=0
_total_time=0
_total_time_str="0"

# _pre_command() will be invoked many times during each display of the
# bash prompt, we need to capture the time only once all that is
# completed and the actual command is about to be executed, this is
# controlled by the flat _at_prompt.
_pre_command() {
  if [ -z "$_at_prompt" ]; then
    # echo N $BASH_COMMAND
    return
  fi
  # echo Y $BASH_COMMAND

  _command_start_time=$(date +%s)
  unset _at_prompt
}

# _post_command() is invoked as part of PROMPT_COMMAND to prepare
# _total_time_str which is then used to compose the proompt display
_post_command() {
  _command_end_time=$(date +%s)
  _total_time=$(($_command_end_time - $_command_start_time))

  local min=60
  local hour=$((60 * $min))
  local day=$((24 * $hour))
  local num_days=$(($_total_time / $day))
  local num_hours=$(($_total_time % $day / $hour))
  local num_mins=$(($_total_time % $hour / $min))
  local num_secs=$(($_total_time % $min))

  _total_time_str=""
  [[ $num_days -gt 0 ]] && _total_time_str="${_total_time_str}${num_days}d "
  [[ $num_hours -gt 0 ]] && _total_time_str="${_total_time_str}${num_hours}h "
  [[ $num_mins -gt 0 ]] && _total_time_str="${_total_time_str}${num_mins}m "
  _total_time_str="${_total_time_str}${num_secs}s"
}

trap '_pre_command' DEBUG

# Simpler prompt for inside chroot (don't call commands)
alias chroot="PROMPT_COMMAND='' PS1='\[\033m\033[36m\]chroot-\u@\h \[\033[33m\w\033[0m\]\n$ ' chroot"

# Source CD history code inplace (used to be separate file)
#
# source acd_func.sh
# acd_func 1.0.6, Peter M., public domain, 16-feb-2005
cd_func() {
  local x2 the_new_dir adir index
  local -i cnt

  if [[ $1 == "--" ]]; then
    dirs -v
    return 0
  fi

  the_new_dir=$1
  [[ -z $1 ]] && the_new_dir=$HOME

  if [[ ${the_new_dir:0:1} == '-' ]]; then
    #
    # Extract dir N from dirs
    index=${the_new_dir:1}
    [[ -z $index ]] && index=1
    adir=$(dirs +$index)
    [[ -z $adir ]] && return 1
    the_new_dir=$adir
  fi

  #
  # '~' has to be substituted by ${HOME}
  [[ ${the_new_dir:0:1} == '~' ]] && the_new_dir="${HOME}${the_new_dir:1}"

  #
  # Now change to the new dir and add to the top of the stack
  pushd "${the_new_dir}" >/dev/null
  [[ $? -ne 0 ]] && return 1
  the_new_dir=$(pwd)

  #
  # Trim down everything beyond 11th entry
  popd -n +11 2>/dev/null 1>/dev/null

  #
  # Remove any other occurence of this dir, skipping the top of the stack
  for ((cnt = 1; cnt <= 10; cnt++)); do
    x2=$(dirs +${cnt} 2>/dev/null)
    [[ $? -ne 0 ]] && return 0
    [[ ${x2:0:1} == '~' ]] && x2="${HOME}${x2:1}"
    if [[ "${x2}" == "${the_new_dir}" ]]; then
      popd -n +$cnt 2>/dev/null 1>/dev/null
      cnt=cnt-1
    fi
  done

  return 0
}

# Conveniences for command `cd'
alias cd=cd_func
export CDPATH=.:..:../..:../../..
alias ..="cd .."
alias ...="cd ../.."
alias ....="cd ../../.."
alias .....="cd ../../../.."

# Powerful combination
md() {
  mkdir -p $1
  cd $1
}

if [[ $BASH_VERSION > "2.05a" ]]; then
  # alt+w shows the menu
  bind -x "\"\M-w\":cd_func -- ;"
fi
# end of acd_func.sh

# ffind [-v] pattern [glob1] [glob2 ...]
# example: ffind printf \*.cpp \*.c \*.h
# example: ffind "pattern with spaces" \*.cpp \*.c \*.h
# example: ffind stdio.h <== search for a file, not text in a file
ffind() {
  [[ -z "${1}" ]] && {
    echo "ffind: missing arguments (pattern)"
    return 2
  }

  if [[ -z "${2}" ]]; then
    # Single argument: search for a file instead of text inside files
    # Pipe through grep for color of the matched pattern
    find . -iname "*${1}*" | \grep ${MY_GREP_OPTIONS} "${1}"
    return 0
  fi

  declare -a flag_verbose
  flag_verbose="n"
  [[ "${1}" == "-v" ]] && {
    flag_verbose="y"
    shift
  }

  declare -a pattern # the search pattern
  declare -a fnames  # fnames in format -name $1 -o -name $2 ...
  fnames=""
  pattern="${1}"
  shift

  # make list of globs in a form suitable for `find'
  # -name glob1 -o -name glob2 -o -name glob3 ...
  while [[ -n "${1}" ]]; do
    [[ -n $fnames ]] && { fnames="${fnames} -o "; }
    fnames="${fnames} -iname ${1}"
    shift
  done

  [[ "${flag_verbose}" == "y" ]] && echo "find . ( ${fnames} )"
  (
    set -f
    find . \( -type f -and ${fnames} \) -print0
  ) | xargs -0 \grep ${MY_GREP_OPTIONS} -i -n -H "${pattern}"

  return 0
}

# calc
# example: calc "3+(4*5)"
calc() {
  echo "$@" | bc -lq
}

# killgrep pattern
killgrep() {
  [[ -z "$1" ]] && {
    echo "killgrep: process name is missing"
    return
  }

  f=${1:0:1}
  rest=${1:1}

  oIFS="${IFS}"
  IFS=$'\n'

  if processes=($(ps ax | grep "[${f}]${rest}")); then
    for p in ${processes[*]}; do
      if [[ "${p}" =~ (^ *[^ ]+).* ]]; then
        pid="${BASH_REMATCH[1]}"
        echo -e "${cyan}process:${NC} ${p}"
        echo -e "${red}kill${NC} ${pid}? (y,n,9,q)"
        read action
        case "${action}" in
          "y")
            echo "kill ${pid}"
            kill ${pid}
            ;;

          "q")
            return
            ;;

          "9")
            echo "kill -9 ${pid}"
            kill -9 ${pid}
            ;;
        esac
      else
        echo "ERROR: didn't manage to obtain the PID from"
        echo "ERROR: ${p}"
      fi
    done
  else
    echo "killgrep: No processes"
  fi

  IFS="${oIFS}"
}

# On Debian, activate preprocessor of binary files or 'less'
# https://manpages.debian.org/bookworm/less/lesspipe.1.en.html
[[ -x /usr/bin/lesspipe ]] && eval "$(SHELL=/bin/sh lesspipe)"

# Arrow-up/-down search history based on a mask, one entry at a time
bind '"\e[A"':history-search-backward
bind '"\e[B"':history-search-forward
#bind Space:magic-space

# alt+r -- search history based on a mask (augments Arrow up):
# alternative shortcut is ctrl+x,ctrl+r
# method 1
#cmd_mhist="\"\C-k\C-ahistory | grep '^ *[0-9]* *\C-e.'\C-m\""
# method 2
cmd_mhist="\"\C-k\C-uhistory | grep \\\"\C-y\\\" \C-m\""
bind '"\M-r"':"$cmd_mhist"
bind '"\C-x\C-r"':"$cmd_mhist"
bind '"\C-xr"':"$cmd_mhist"

# alt+k -- paste current command line into history and begin new line
# alternative shortcut is ctrl+x,ctrl+k
cmd_hist="\"\C-ahistory -s '\C-e'\C-m\""
bind '"\M-k"':"$cmd_hist"
bind '"\C-x\C-k"':"$cmd_hist"
bind '"\C-xk"':"$cmd_hist"

# ctrl+xPgUp: show last 25 entries of the history
# alternative shortcut is ctrl+x,ctrl+l
# (erase the line first)
bind '"\C-x\e[5~"':"\"\C-k\C-uhistory | tail -25\C-m\""
bind '"\C-x\C-l"':"\"\C-k\C-uhistory | tail -25\C-m\""

# Now map xterm's alternative keybindings to existing functionality
# Some are simple translations to correspontend M- combinations
# ctrl+left/right arrows:
bind '"\e\x5b\x31\x3b\x35\x44"':backward-word
bind '"\e\x5b\x31\x3b\x35\x43"':forward-word
bind '"\x1b\x5b\x35\x44"':backward-word
bind '"\x1b\x5b\x35\x43"':forward-word
# alt+b/f: the usual word navigation but in xterm terms
bind '"\xe2"':backward-word
bind '"\xe6"':forward-word
# atl+backspace:
bind '"\xff"':backward-kill-word
# alt+'.':
bind '"\xae"':yank-last-arg
bind '"\xe2\x89\xa5"':yank-last-arg
# alt+k:
bind '"\xeb"':"$cmd_hist"
# alt+r:
bind '"\xf2"':"$cmd_mhist"

# On the Mac, map Option+Left/Right
bind '"\x1b\x1b[D"':backward-word
bind '"\x1b\x1b[C"':forward-word

unset cmd_hist cmd_mhist

# One downside is that inputrc wouldn't bet set until after the first
# time .bashrc runs
if [[ ! -f ~/.inputrc ]]; then
  echo "set colored-completion-prefix on" >>~/.inputrc
fi

# Don't use ^D to exit
set -o ignoreeof

# Don't put duplicate lines in the history.
export HISTCONTROL=ignoredups

# Don't put 'history' commands themselves in the history
export HISTIGNORE='history*'

# Kepp no more than 1000 lines
export HISTFILESIZE=1000
export HISTSIZE=1000

# Append, don't overwrite history
shopt -s histappend

# Check window size after each command to avoid annoying effects of resizing
shopt -s checkwinsize

# A command name that is the name of a directory is executed as if it
# were the argument to the cd command.
# shopt -s autocd

# Write history before accepting a new command
# Then read back the merged list
export PROMPT_COMMAND='__r=$?; _post_command; set_prompt $__r "$_total_time_str"; _xtitle; history -a; history -c; history -r; _at_prompt=1;'

# Show directories bold, everything else is normal
if [[ "${the_os}" == "Darwin" || "${the_os}" == "FreeBSD" ]]; then
  export LSCOLORS="Exxxxxxxxxxxxxxbadxxxx"
else
  # 90 (darkgray) explicitely needed for Mac terminal, 00 is good otherwise
  export LS_COLORS="no=00:fi=00:di=01:ln=00:pi=00:so=00:bd=00:cd=00:or=00:ex=00"
fi

# disable XON/XOFF flow control (^s/^q)
stty -ixon

# This is more objective than the builtin $SHLVL
if [[ -z $BASH_NEST ]]; then
  export BASH_NEST=0
else
  ((BASH_NEST++))
fi

# print
echo -e "${cyan}GNU Bash: ${red}v${BASH_VERSION%.*}${cyan}" \
  " | bashrc: ${red}v${bashrc_v}${cyan} |  nest level: ${red}${BASH_NEST}${NC}"

# source_if_exists:
# Checks if a file exists and runs 'source'
source_if_exists() {
  sh_file=$1
  [[ -r ${sh_file} ]] && source ${sh_file}
}

#
# Activate bash_completions if appropriate
source_if_exists "/usr/share/bash-completion/bash_completion"
source_if_exists "/usr/share/bash-completion/completions/git"
# To install git completions on the Mac do 'brew install git'
# To install bash completions do 'brew install bash-completion@2'
source_if_exists "/opt/homebrew/etc/profile.d/bash_completion.sh"
source_if_exists "/opt/homebrew/Cellar/git/2.38.1/share/zsh/site-functions/git-completion.bash"

# _xtitle: sets title
# no arguments (and no $MANUAL_TITLE) sets the title to current dir
_xtitle() {
  a="$1"
  host="$2"
  if [[ -n $MANUAL_TITLE ]]; then
    a="$MANUAL_TITLE"
  else
    # auto is current directory, replace $HOME with ~
    [[ -z $a ]] && a="${PWD/$HOME/~}"
  fi
  case "$TERM" in
    *term | rxvt | cygwin | xterm-*)
      ssh_str_title=""
      # Use generic host name
      host_str=$(hostname -s)
      # Or overwrite with DNS if present
      [[ ! -z "${SSH_CONNECTION}" ]] && ssh_str_title="@${host_str}:"
      echo -n -e "\033]0;${ssh_str_title}$a\007"
      ;;
    screen)
      # add [screen] to the window title & change term name in screen's list
      echo -n -e "\033]0;$a[screen]\007"
      ;;
    *) ;;
  esac
}

# by default no manual title block
unset MANUAL_TITLE

# xtitle: for manual set of title, this blocks _xtitle from
# doing auto set
# call with no parameters to reset to auto
xtitle() {
  a="$1"
  if [[ -z "$a" ]]; then
    unset MANUAL_TITLE
  else
    MANUAL_TITLE="$a"
    _xtitle
  fi
}

# changes window title to the command that is executed
# could be used as a wrap for execution of any command
title_cmd() {
  s=$MANUAL_TITLE
  unset MANUAL_TITLE
  xtitle "$*"
  $*
  MANUAL_TITLE=$s
}

# for programs that involve user interaction (like doc browsing)
# or take longer time (like compilations) it is good to
# supply a more informative title
# ADD here commands for which you wish to supply better title
alias pinfo="title_cmd pinfo"
alias info="title_cmd info"
alias man="title_cmd man"
alias make="title_cmd make"
alias less="title_cmd less"
alias more="title_cmd more"
# find's cmd line is too complicated to prefix
# alias find="title_cmd find"
alias ping="title_cmd ping"
alias vim="title_cmd vim"
alias vi="title_cmd vi"
alias emacs="title_cmd emacs"
alias ftp="title_cmd ftp"
alias ncftp="title_cmd ncftp"
alias wget="title_cmd wget"
alias telnet="title_cmd telnet"

# Customize for GNU Info
# TODO: Rework path_once() to work for other PATH-type variables, use that here
if [[ -z "$INFOPATH" ]]; then
  export INFOPATH=~/.local/share/info:/usr/share/info
else
  export INFOPATH=${INFOPATH}:~/.local/share/info:/usr/share/info
fi
# Enable colors for GNU Info
if [[ ! -f ~/.infokey ]]; then
  echo "#var" >~/.infokey
  echo "link-style=blue,bold" >>~/.infokey
  echo "active-link-style=yellow,standout" >>~/.infokey
  echo "match-style=bold" >>~/.infokey
fi

# restore "bind" command
[[ "${TERM}" == "dumb" ]] && unalias bind

# The preferred place for config/data files
# (avoid poluting top level $HOME,
# see https://0x46.net/thoughts/2019/02/01/dotfile-madness/ for details)
export XDG_DATA_HOME="$HOME/.local/share"
export XDG_CONFIG_HOME="$HOME/.config"
export XDG_CACHE_HOME="$HOME/.cache"
[[ ! -d $XDG_DATA_HOME ]] && mkdir -p $XDG_DATA_HOME
[[ ! -d $XDG_CONFIG_HOME ]] && mkdir -p $XDG_CONFIG_HOME
[[ ! -d $XDG_CACHE_HOME ]] && mkdir -p $XDG_CACHE_HOME
# Now for programs that don't recognize $XDG_xxx
export LESSHISTFILE="$XDG_CONFIG_HOME/less/history"
[[ ! -d $XDG_CONFIG_HOME/less ]] && mkdir -p $XDG_CONFIG_HOME/less

# Activate fzf if installed
if [[ $(uname) =~ "Linux" ]]; then
  # Enable fzf keybindings
  source_if_exists "/usr/share/doc/fzf/examples/key-bindings.bash"
  # Enable fuzzy auto-completion for Bash:
  source_if_exists "/usr/share/doc/fzf/examples/completion.bash"
else
  # MacOS?
  source_if_exists ~/.config/fzf/fzf.bash
fi

# Rust
source_if_exists ~/.cargo/env

# Chain with other settings
#
# (This is suitable for a common .bashrc to be shared on many
# platforms where any domain specific settings can put in .bashrc2)
[ -f ~/.bashrc2 ] && source ~/.bashrc2
