# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples
# shellcheck disable=SC3044

# If not running interactively, don't do anything
case "$-" in
  *i*) ;;
  *) return ;;
esac

# [ -n "${ENV-}" ] || . "${HOME%/}"'/.profile'
# shellcheck source=.rc
[ -r "${HOME%/}"'/.rc' ] && . "${HOME%/}"'/.rc'

# don't put duplicate lines or lines starting with space in the history.
# See bash(1) for more options
HISTCONTROL=ignoreboth

# append to the history file, don't overwrite it
shopt -s histappend

# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
# HISTSIZE=1000
# HISTFILESIZE=2000

# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize

# If set, the pattern "**" used in a pathname expansion context will
# match all files and zero or more directories and subdirectories.
#shopt -s globstar

# make less more friendly for non-text input files, see lesspipe(1)
#[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"

# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
  debian_chroot=$(cat /etc/debian_chroot)
fi

# set a fancy prompt (non-color, unless we know we "want" color)
# shellcheck disable=SC2249
case "${TERM}" in
  xterm-color | *-256color) color_prompt=yes ;;
esac

# uncomment for a colored prompt, if the terminal has the capability; turned
# off by default to not distract the user: the focus in a terminal window
# should be on the output of commands, not on the prompt
force_color_prompt=yes

if [ -n "${force_color_prompt}" ]; then
  if [ -x /usr/bin/tput ] && tput setaf 1 >/dev/null 2>&1; then
    # We have color support; assume it's compliant with Ecma-48
    # (ISO/IEC-6429). (Lack of such support is extremely rare, and such
    # a case would tend to support setf rather than setaf.)
    color_prompt=yes
  else
    color_prompt=
  fi
fi

if [ "${color_prompt}" = yes ]; then
  PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w \$\[\033[00m\] '
else
  PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt force_color_prompt

# If this is an xterm set the title to user@host:dir
case "${TERM}" in
  xterm* | rxvt*)
    PS1="\[\e]0;${debian_chroot:+(${debian_chroot})}\u@\h: \w\a\]${PS1}"
    ;;
  *) ;;
esac

# enable color support of ls and also add handy aliases
# if [ -x /usr/bin/dircolors ]; then
#   # test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"
#   alias ls='ls --color=auto'
#   #alias dir='dir --color=auto'
#   #alias vdir='vdir --color=auto'
#
#   alias grep='grep --color=auto'
#   alias fgrep='fgrep --color=auto'
#   alias egrep='egrep --color=auto'
# fi

# colored GCC warnings and errors
#export GCC_COLORS='error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01'

# some more ls aliases
#alias ll='ls -l'
#alias la='ls -A'
#alias l='ls -CF'

# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.

# if [ -f ~/.bash_aliases ]; then
#   . ~/.bash_aliases
# fi

# enable programmable completion features (you don't need to enable
# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
# sources /etc/bash.bashrc).
# if ! shopt -oq posix; then
#   if [ -f /usr/share/bash-completion/bash_completion ]; then
#     . /usr/share/bash-completion/bash_completion
#   elif [ -f /etc/bash_completion ]; then
#     . /etc/bash_completion
#   fi
# fi

# encoding
export LANG=en_US.UTF-8

# editor
if command -v nvim >/dev/null 2>&1; then
  export EDITOR=nvim
elif command -v vim >/dev/null 2>&1; then
  export EDITOR=vim
else
  export EDITOR=vi
fi
export VISUAL="${EDITOR}"
export FCEDIT="${EDITOR}"

# pager
export LESSHISTFILE='-'
# export LESS='-XRj4-+I'
export PAGER=less
export GROFF_NO_SGR=1

# history
# HISTCONTROL=ignoredups
HISTIGNORE="&:[ ]*:[bf]g:cd:exit:history:ls"
# ignore duplicates - one/two letter commands
# HISTIGNORE="@(?|??|???)*( |$'\t'):*( |$'\t')"
# TIMEFORMAT='%3lR'
unset MAILCHECK
# do not save command to history file
unset HISTFILE

# prompt
PROMPT_DIRTRIM=2
# PS1='\w \$ '
# shellcheck disable=SC2154
PS1='\[\033]0;${SSH_CONNECTION:+\h:}\W\a\]${?#0}\w \$ '
# PS1='\[\033]0;${SSH_CLIENT:+\\h:}\W\a\]
# ${?#0}$ '

# PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ '
# PS1='\u@\h:\w \$ '
# if [ -n "${SSH_CLIENT}" ] || [ -n "${SSH_CONNECTION}" ]; then
#   PS1='[\u@\h \w]'${PS1}
# fi
## title
# case ${TERM} in
#   linux*|cons*) ;;
#   *) PS1='\[\033]0;\w\007\]' ;;
# esac

# options
stty -ixon 2>/dev/null
# only logout if <ctrl-d> is executed two consecutive times
IGNOREEOF=1
set -o noclobber
# set -o notify
# shellcheck disable=SC3044
shopt -s autocd 2>/dev/null
CDPATH="."

# readline
if [ -n "${INPUTRC-}" ] || [ -f "${HOME%/}"'/.config/readline/inputrc' ]; then
  bind -f "${INPUTRC:-${HOME%/}/.config/readline/inputrc}"
else
  bind Space:magic-space
  bind TAB:menu-complete
  bind '"\e[Z": menu-complete-backward'
  bind '"M-TAB": dynamic-complete-history'
  bind '"\e[A": history-search-backward'
  bind '"\e[B": history-search-forward'
  bind '"\C-a": beginning-of-line'
  bind '"\C-b": backward-char'
  bind '"\C-e": end-of-line'
  bind '"\C-f": forward-char'
  bind '"\C-k": kill-line'
  bind '"\C-l": clear-screen'
  bind '"\C-]": dabbrev-expand'
  bind '"\C-xa": alias-expand-line'
  bind '"\C-xd": dump-macros'
  bind '"\C-xe": shell-expand-line'
  bind '"\C-x\C-k": kill-whole-line'
  bind '"\C-x\C-u": undo'
  bind '"\e.": insert-last-argument'
  bind '"\ee": edit-and-execute-command'
  bind '"\en": history-substring-search-forward'
  bind '"\ep": history-substring-search-backward'
  bind '"\eu": undo'
  bind '"\e\C-e": shell-expand-line'
  # macros | convenient shell interaction
  bind '"\C-g": "fg\C-m"'
  bind '"\C-x\/": "; echo $?"'
  bind '"\C-x\`": "\$\(\)\C-b"'
  bind '"\C-xb": "\$\{\}\C-b"'
  bind '"\C-xl": "\C-e | less\C-m"'
  bind '"\e\"": "\e[1;3D\"\C-e\""'
  bind '"\ea": "\C-a\e[3;5~"'
  bind '"\es": "\C-a(set -x ; \C-e)\C-b"'
  bind '"\ev": "\C-e | vi -\C-m"'
  bind '"\eH": " --help"'
  bind '"\eV": " --version"'
  bind '"\eX": "\$\(!! \| tail -1\)\e\C-e"'
  bind '"\eOP": "\C-a\man \C-e\C-m"'
fi

# using OSC52
_copybuffer() {
  # shellcheck disable=SC2312
  printf '\e]52;c;%s\a' "$(printf %s "${READLINE_LINE}" | openssl base64 -A)"
}
bind -x '"\C-o": _copybuffer'

_run_help() { help "${READLINE_LINE-}" 2>/dev/null || man "${READLINE_LINE-}"; }
bind -m emacs -x '"\eh": _run_help'
bind -m vi-insert -x '"\eh": _run_help'

# auto-quote current line
_quote_all() {
  READLINE_LINE="${READLINE_LINE@Q}"
  READLINE_POINT=0
}
bind -x '"\eq": _quote_all'

# alias
# sudo
alias -- sudo='sudo '
# `sudo -Es`. privileged-shell: this will start shell as `root`
# with your rc files and `$HOME` will point to your regular home directory.
alias usudo='sudo -E -s '
alias svi='usudo vim'
alias svim='svi'

# dotfiles
alias d.='cd "${DOTFILES-}"'
alias stowh='stow --target="${HOME%/}"'
alias stowd='stow --delete'
alias stowv='stow --verbose=2 --simulate'

# cdx
# shellcheck disable=SC2154
alias dow='cd "${XDG_DOWNLOAD_DIR-}"'
alias xbin='"${HOME%/}"'\''/.local/bin'\'''
alias config='"${XDG_CONFIG_HOME-}"'
alias data='"${XDG_DATA_HOME-}"'
alias state='"${XDG_STATE_HOME-}"'
# data directory aliases
# shellcheck disable=SC2034
xdh="${XDG_DATA_HOME-}"
# shellcheck disable=SC2034
xch="${XDG_CONFIG_HOME-}"
# shellcheck disable=SC2034
xsh="${XDG_STATE_HOME-}"
alias xdh='cd "${XDG_DATA_HOME-}"'
alias xch='cd "${XDG_CONFIG_HOME-}"'
alias xsh='cd "${XDG_STATE_HOME-}"'

# cd
alias -- 1='cd -- "${OLDPWD:--}"' -='cd -- "${OLDPWD:--}"'
alias -- ...='cd -- ../..'
alias -- ....='cd -- ../../..'
alias -- .....='cd -- ../../../..'
alias -- ......='cd -- ../../../../..'
alias -- .......='cd -- ../../../../../..'
alias -- ........='cd -- ../../../../../../..'
alias -- .........='cd -- ../../../../../../../..'

# editor
# alias v='vim -u DEFAULTS --cmd '\''set lpl rnu nu hid ar ai si scs ic et ts=2 sw=2 bs=2 | nmap Y y$'\'''
# alias v='"${EDITOR:-vi}" -i NONE'
alias vi='"${EDITOR:-vi}" -i NONE'
# alias vim='"${EDITOR:-vi}"'
# alias vimrc='v "${HOME%/}"'\''/.vim/vimrc'\'''
alias vimrc='"${EDITOR:-vi}" "${HOME%/}"'\''/.config/vim/vimrc'\'''

# ls
# alias ls='ls --color=auto'
alias ll='ls -lAF'
alias la='ls -lAF'
alias l='ls -ACF'
alias lg='ls -lAh | grep -i'

# shortcut
alias b='cat'
alias d='type'
command -v g >/dev/null 2>&1 || alias g='git'
alias x='exit'

# unix
alias cp='cp -i'
alias csort='LC_ALL=C sort'
command -v -- cdiff >/dev/null 2>&1 || alias dif='git diff --no-index'
# alias dif='diff --color=always --side-by-side --report-identical-files'
alias diff='diff --color=auto'
# alias grep='LANG=C grep --color=auto'
alias -- md >/dev/null 2>&1 && unalias -- md
alias -- md='command -p -- mkdir -p'
alias -- mv='mv -i'
alias rm='rm -i'
alias rmd='command -p -- rm -d'
command -v tree >/dev/null \
  || alias tree='ls -R | grep ":$" | sed -e "s/:$//" -e "s/[^-][^\/]*\//--/g" -e "s/^/ /" -e "s/-/|/"'

# vars
alias alg='alias | grep'
alias allg='(env && set) | grep'
alias cls='clear && printf "\e[3J"'
alias cmdv='command -v'
alias ec='echo'
alias envg='env | grep'

# utility
alias dud='command du -d 1 | sort -n | numfmt --from-unit=512 --to=iec --format="%6.1f"'
alias fd='fd --hidden'
alias fdd='fd -td'
alias fdg='fd --glob'
alias fontfamilies='fc-list --format='\''%{family}\n'\'' | sed '\''s/,.*//'\'' | sort -u'
alias fonts='fc-list | sed '\''s,:.*,,'\'' | sort -u'
alias fontsterm='fc-list '\'':'\'' family spacing outline scalable | grep -e spacing=100 -e spacing=90 | grep -e outline=True | grep -e scalable=True'
alias manword='man --where --global-apropos --match-case'
#alias ppath='echo $PATH | tr -s ":" "\n"'
alias ppath='command printf -- '\''%s\n'\'' "${PATH-}" | command sed -e '\''s/:/\n/g'\'
alias psg='ps ax -o pid,tty,time,stime,comm | grep -v grep | grep'
alias rgs='rg --hyperlink-format=kitty --case-sensitive'
alias rgu='rg --hyperlink-format=kitty --unrestricted'
alias rgv='rg --invert-match'
alias y='yank'

# shell
alias bashrc='v "${HOME%/}"/.bashrc'
alias envrc='v "${HOME%/}"/.rc'
alias pass='export WAYLAND_DISPLAY=wayland-0; pass'
alias profilerc='v "${HOME%/}"/.profile'
alias reload='. "${HOME%/}"'\''/.bashrc'\'''
alias sshaddl='ssh-add -L'
alias sshconf='v "${HOME%/}"/.ssh/config'
# alias tm='tmux set -g allow-passthrough on && tmux set -g prefix C-Space && tmux bind C-Space send-prefix; tmux attach || tmux new-session 2>/dev/null'

# network
alias amim='curl -s "https://am.i.mullvad.net/json" | jq'
alias amim4socks='curl -s --socks5-hostname 10.64.0.1 "https://ipv4.am.i.mullvad.net/json" | jq'
alias amim6socks='curl -s --socks5-hostname 10.64.0.1 "https://ipv6.am.i.mullvad.net/json" | jq'
alias check_tor='curl -x socks5h://localhost:9050 -s https://check.torproject.org/api/ip'
alias ifactive='ifconfig | pcregrep -M -o '\''^[^\t:]+:([^\n]|\n\t)*status: active'\'''
alias inet='ip -o -4 route show to default 2>/dev/null | tr '\''[:space:]'\'' '\''\n'\'' | sed -n '\''/dev/{n;p}'\'''
alias interface='netstat -r | grep default | field NF'
alias ipeth='ip -j addr show dev eth0 | jq -r '\''.[0].addr_info | map(select(.family == "inet"))[0].local'\'''
alias iplocal='ifconfig | grep -Eo '\''inet (addr:)?([0-9]*\.){3}[0-9]*'\'' | grep -Eo '\''([0-9]*\.){3}[0-9]*'\'' | grep -v '\''127.0.0.1'\'''
alias ipwlan='ip -j addr show dev wlan0 | jq -r '\''.[0].addr_info | map(select(.family == "inet"))[0].local'\'''
alias localip='ip addr show | grep -E '\''(ens|eth|wlan)'\'' | grep -oP '\''(?<=inet\s)\d+(\.\d+){3}'\'' | head -1'
alias mydns='grep -v -E "^\s*(#|$)" "/etc/resolv.conf"'
alias myip='curl -sq "https://ifconfig.co/ip"'
alias netls='netstat --listening --program --tcp'
alias netll='ss --all --listening --processes --tcp'
alias onport='ss --all --listening --numeric sport \='
alias openports='netstat -lntu'
alias ping='ping -nc 5'
alias ping6='ping6 -nc 5'
# lsof -iTCP -sTCP:ESTABLISHED -sTCP:LISTEN -n -P | awk '{print $1, substr($0, index($0,$9))}'
alias portsl='lsof -iTCP -sTCP:LISTEN -n -P'
alias proxychains='proxychains4 -q'
alias routing4='netstat -Wrnf inet'
alias routing6='netstat -Wrnf inet6'
alias sockstat='netstat --listening -n --program --tcp --udp --protocol=inet,unix'
alias toron='. torsocks on'
alias wget='wget --no-hsts'

# linux
## apt
alias apps='cd /etc/apt/sources.list.d'
alias applications='cd /usr/share/applications'
alias aptdeps='apt depends'
alias apthist='zless $(ls -v /var/log/dpkg.log*) | sort -r | less'
# alias aptirdeps='apt-cache --installed --implicit rdepends'
alias aptirdeps='apt-cache --installed --no-recommends --no-suggests rdepends'
alias aptrdeps='apt rdepends'
alias aptl='apt list --installed'
alias aptlg='apt list --installed | grep -e'
aptn() { command apt search "^$1" -n; }
alias aptpkg='apt-cache showpkg'
aptrep() { apt list "?narrow(?origin(\"$1\"))"; }
alias apts='apt search'
alias aptsrc='apt showsrc'
alias aptw='apt show'
alias dpkgl_residual='dpkg --list | grep "^rc" | field 2'
# shellcheck disable=SC2154
alias dpkgls_bysize='dpkg-query --show --showformat='\''${Installed-Size}\t${Package}\n'\'' | sort -n'
alias find_leftovers='find /etc -name '\''*.dpkg-*'\'' -o -name '\''*.ucf-*'\'' -o -name '\''*.merge-error'\'''
## log
### journalctl
alias bootlog='journalctl --no-hostname --boot --lines=500'
alias daemonlog='journalctl --boot --no-pager --unit'
alias daemonfollow='journalctl --follow --boot --no-pager --unit'
alias errors='journalctl --boot --priority 3'
alias jog='journalctl --boot --grep'
alias jor='journalctl'
alias jorcat='journalctl --output=cat --unit'
alias jordbg='journalctl --no-pager --boot --grep="fail|emerg|alert|crit|error|warn"'
alias jortoday='journalctl --catalog --pager-end --since=today'
alias logs='journalctl --no-hostname --output=short --pager-end --unit'
alias logsverbose='journalctl --output=verbose --unit'
alias msg='dmesg --human'
alias sessionstatus='loginctl session-status'
alias tailall='tail -f $(find /var/log -type f | grep -v ".gz$")'
### systemctl
alias daemonreload='sudo systemctl daemon-reload'
alias reloadsysctl='sudo sysctl --system'
alias sc='sudo systemctl'
alias sce='sudo systemctl enable --now'
# alias sced='sudo --preserve-env=EDITOR systemctl edit'
alias sced='sudo systemctl edit'
alias scr='sudo systemctl daemon-reload && sudo systemctl reload-or-restart'
alias scs='sudo systemctl status'
alias scw='sudo systemctl show'
## `systemctl --user`
alias scu='command systemctl --user'
alias scus='command systemctl --user status'
alias scudaemonreload='systemctl --user daemon-reload'
alias scufailed='systemctl --user --failed --no-legend --plain'
alias scuenv='systemctl --user show-environment'
### systemd
# easily identify a dodgy init system
alias badinit='[ "$(ps -p 1 --format '"'"'comm='"'"')" = "systemd" ]'
alias syscat='systemd-analyze cat-config /etc/systemd/system/'
### rpi
if uname -a | grep -q 'rpi' >/dev/null; then
  ## apt
  alias aptar='sudo apt-get remove "?garbage"'
  alias aptgi='sudo apt-get install'
  alias apti='sudo apt install'
  alias aptr='sudo apt remove'
  alias aptx='sudo apt --purge remove'
  alias purgeleftovers='sudo apt purge "?config-files"'
  ## hardware
  # find and list disks
  alias alldisks='sudo df -h -T --exclude-type=tmpfs --exclude-type=devtmpfs --exclude-type=overlay --exclude-type=squashfs && sudo blkid'
  alias fdisks='sudo fdisk --list'
  # lsblkl: more lsblk info
  alias lsblkl='lsblk --output=NAME,RO,SIZE,FSTYPE,RM,TYPE,MOUNTPOINT,LABEL,VENDOR,MODEL'
  alias lsblktree='lsblk --output=NAME,TYPE,FSTYPE,LABEL,SIZE,SCHED,FSUSE%,MOUNTPOINT --sort=START --tree'
  alias llblkl='sudo lsblk --output=UUID,NAME,FSTYPE,SIZE,MOUNTPOINT,LABEL,MODEL'
  alias lspci='sudo lspci'
  alias lshw='sudo lshw'
  alias nvme='sudo nvme'
  alias nvmeidentify='nvme id-ns /dev/nvme0n1 --human-readable'
  alias pcidevices='lspci -PP'
  alias pciinfo='lspci -nn -v'
  alias pcilinkstat='lspci -vvv | grep -E '\''nvme|LnkSta'\'''
  alias umnt='udisksctl unmount --block-device'
  alias usbtree='lsusb --tree'
  ## network
  alias maceth='nmcli --fields GENERAL.HWADDR device show eth0 | field 2'
  alias macwifi='nmcli --fields GENERAL.HWADDR device show wlan0 | field 2'
  alias ufw='sudo ufw'
  alias ufwl='ufw show listening'
  alias ufwn='ufw status numbered'
  alias ufws='ufw status'
  alias ufwt='ufw allow in on tailscale0 to any'
  alias ufwv='ufw status verbose'
  alias wifi_powersave_get='iw dev wlan0 get power_save'
  alias wifi_powersave_off='iw dev wlan0 set power_save off'
  alias wifi_powersavingoff='iwconfig wlan0 power off'
  ## pi
  # screen-blanking: cat /sys/module/kernel/parameters/consoleblank
  alias rpi_fw='vcgencmd version'
  # cat /proc/cmdline
  alias rpi_img='cat /etc/rpi-issue'
  alias rpi_temp='vcgencmd measure_temp'
  alias rpi_voltage='vcgencmd pmic_read_adc EXT5V_V'
  # cat /boot/firmware/config.txt | grep -E -v "^\s*(#|^$)"
  alias rpi_get_config='vcgencmd get_config int && vcgencmd get_config str'
  alias rpitree='cat /proc/device-tree/compatible | tr '\''\0'\'' '\''\n'\'''
  ## rpi-admin
  alias rpieepromupdate='sudo -E rpi-eeprom-config --edit'
  alias raspiconfig='sudo raspi-config'
  alias pins='sudo pinctrl 2>&1'
  ## caddy
  alias cadfile='sudo -E -s vim /etc/caddy/Caddyfile'
  alias cadfmt='sudo caddy fmt --overwrite /etc/caddy/Caddyfile \
    && sudo caddy --config=/etc/caddy/Caddyfile'
  alias cadenvfmt='sudo caddy fmt --overwrite /etc/caddy/Caddyfile \
    && sudo caddy validate --envfile=/etc/caddy/.env --config=/etc/caddy/Caddyfile'
fi

# rust
# command cargo install --list | grep -v '[0-9]' | field 1
alias cargols='command cargo install --list 2>/dev/null'

# trash-cli
alias rr='trash-put'
alias rre='trash-empty'
alias rrl='trash-list'
alias rrr='trash-restore'
alias rrm='trash-rm'
alias rrold='find . -type f -mtime +100 -exec trash-put {} +'

# py
alias pip='pip3'
alias py='python3'

# uv
alias uvexp='uv export --format requirements-txt --no-hashes --output-file requirements.txt --quiet'
alias uvp='uv pip'
alias uvr='uv run'
alias uvrp='uv run python'
alias uvs='uv sync'
alias uvsr='uv sync --refresh'
alias uvsu='uv sync --upgrade'
alias uvt='uv tool'
alias uvtl='uv tool list'
alias uvtup='uv tool upgrade --all'
alias uvup='uv self update'
alias uvv='uv venv'

# apps
alias bang='ddgr --noprompt'
alias ddgr='ddgr --expand'
alias irssi='irssi --config="${XDG_CONFIG_HOME-}"/irssi/config --home="${XDG_DATA_HOME-}"/irssi'
alias -- t >/dev/null 2>&1 && unalias -- t
alias -- t='tailscale'

if command -v tailscale >/dev/null 2>&1; then
  alias t_derpmap='curl --silent "https://login.tailscale.com/derpmap/default" | jq'
  alias t_funs='tailscale funnel status'
  alias t_get='tailscale file get "${HOME%/}/cloud"'
  alias t_hosts='tailscale status --json | jq --raw-output '\''[.Peer | to_entries[] | .value.DNSName]'\'' | jq --join-output '\''[ join(" ")]'\'''
  alias t_lockstatus='tailscale lock status --json | jq --raw-output '\''.Enabled'\'' | grep -q true >/dev/null && jq --join-output '\''.FilteredPeers | map(.NodeKey) | join("\n")'\'''
  alias t_lookup='dig @100.100.100.100 +noall +answer +short -x  $(tailscale ip -1)'
  alias t_name='tailscale status --self --json | jq --raw-output .Self.DNSName | sed '\''s/\.$//'\'''
  alias t_nodename='tailscale status --self --json | jq --raw-output '\''.Self.DNSName'\'' | cut --delimiter . --fields 1'
  alias t_servelocal='tailscale serve --bg --http 10000 localhost:8080'
  # note: [ $status = "Running" ]
  alias t_state='tailscale status --json | jq --raw-output '\''.BackendState'\'''
  alias t_stats='tailscale status --json --active'
  alias t_suffix='tailscale status --json | jq --raw-output '\''.MagicDNSSuffix'\'''

  fix_resolv_tailscale() {
    sh -c -- 'sudo ln -sf ../run/systemd/resolve/stub-resolv.conf /etc/resolv.conf'
    sudo systemctl restart systemd-resolved
    sudo systemctl restart NetworkManager
    sudo systemctl restart tailscaled
  }

  # /run/systemd/resolve/stub-resolv.conf contains the local stub 127.0.0.53
  # as the only DNS server and a list of search domains
  # this is the recommended mode of operation that propagates systemd-resolved
  # managed configuration to all clients
  fix_resolvstub() {
    sh -c -- 'sudo ln -sf ../run/systemd/resolve/stub-resolv.conf /etc/resolv.conf'
    sudo systemctl restart systemd-resolved.service
  }
  fix_resolvnostub() {
    sh -c -- 'sudo sed -i -r 's/^#?DNSStubListener=.*/DNSStubListener=no/' /etc/systemd/resolved.conf'
    sh -c -- 'sudo ln -sf ../run/systemd/resolve/resolv.conf /etc/resolv.conf'
    sudo systemctl restart systemd-resolved.service
  }

  is_tailpeer_alive() {
    if [ "$#" -eq 0 ]; then
      printf '%s\n' "$0: [peer_name]"
    else
      ping -4 -c 1 -w 2 "$1" >/dev/null && return 0
      tailscale ping --timeout 2s --c 1 --until-direct=false "$1" >/dev/null \
        && return 0 || return 1
    fi
  }

  is_tailscale_running() {
    tailscale_status="$(tailscale status --json | jq --raw-output '.BackendState')"
    echo "${tailscale_status}"
  }

  tenv() {
    TS_IP="$(tailscale ip -1)"
    TS_MAGICDNS="$(tailscale status --self --json | jq --raw-output '.MagicDNSSuffix')"
    TS_DOMAIN="$(tailscale status --self --json | jq --raw-output '.CertDomains[0]')"
    TS_NODE="$(tailscale status --self --json | jq --raw-output '.Self.HostName')"
    TS_NAME="$(tailscale status --json | jq --raw-output '.Self.DNSName | .[:-1]')"
    export TS_IP
    export TS_DOMAIN
    export TS_MAGICDNS
    export TS_NAME
    export TS_NODE
  }
  # tailscaled
  alias tailscalednolog='tailscaled --no-logs-no-support'
fi

if [ -d "${HOME%/}"'/.config/shell' ]; then
  # shellcheck source=.config/shell/aliases.sh
  . "${XDG_CONFIG_HOME-}"'/shell/aliases.sh'
  # shellcheck source=.config/shell/darwin.sh
  . "${XDG_CONFIG_HOME-}"'/shell/'"${OS-}"'.sh'
  # shellcheck source=.config/shell/functions.sh
  . "${XDG_CONFIG_HOME-}"'/shell/functions.sh'
  # shellcheck source=.config/shell/lib.sh
  . "${XDG_CONFIG_HOME-}"'/shell/lib.sh'
  # shellcheck source=.config/shell/libgit.sh
  . "${XDG_CONFIG_HOME-}"'/shell/libgit.sh'
fi

# completion | enable programmable completion features
# shellcheck source=/dev/null
if ! shopt -oq posix; then
  if [ -f /usr/share/bash-completion/bash_completion ]; then
    . /usr/share/bash-completion/bash_completion
  elif [ -f /etc/bash_completion ]; then
    . /etc/bash_completion
  fi
  # make bash complete `g` alias just like it does `git`.
  # __git_complete g git
  # load dynamically loaded completion functions (may not be required)
  _completion_loader git
  # copy the original statement, but replace the last command (git) with your alias (g)
  # shellcheck disable=SC3044
  complete -o bashdefault -o default -o nospace -F __git_wrap__git_main g
  complete -o bashdefault -o default -F _comp_command d
fi

# shellcheck disable=SC3044
# complete -c all d
# complete -d take mkcd
# complete -A setopt set
# complete -P '%' -j fg jobs kill
# complete -F __start_tailscale t

# user completions
BASH_COMPLETION_USER_DIR="${HOME%/}/.local/share/bash-completion"
for file in "${BASH_COMPLETION_USER_DIR-}"/*; do
  # shellcheck disable=SC1090
  . "${file-}" 2>/dev/null
done

# functions
# shellcheck disable=SC2312
cdtmp() { cd "$(mktemp -d)" || return; }

conf() {
  for p in "${XDG_CONFIG_HOME-}"/$1; do
    if [ -d "${p}" ]; then
      ls -H "${p}"
    else
      v "${p}"
    fi
  done
}
# alias conf='noglob conf'

cx() { chmod +x "$*"; }

diffy() {
  command diff --side-by-side --suppress-common-lines \
    --width="$((COLUMNS / 2 - 1 + COLUMNS / 2 - 1))" "${@-}"
}

dua() {
  command -p -- du -d 1 | sort -n \
    | awk '{split("k m g",v); s=1; while($1>1024){$1/=1024; s++} print int($1)" "v[s]"\t"$2}'
}

ecc() {
  "$*"
  echo $?
}

# f() { find . -iname "*$1*" 2>/dev/null; }
# ff() { find . -type f -iname '*'"$*"'*'; }

ff() {
  command find -L -- . \
    -path '*/.git' -prune -o -path '*/.nc_plugin' -prune -o -iname '*'"$*"'*' \
    -type f -print 2>/dev/null
}

command -v -- field >/dev/null 2>&1 || field() { awk "{print \$$1}"; }

# print who uses the given file. filesu [filepath]
filesu() {
  lsof "$1" 2>/dev/null | awk 'NR > 1 {print $1"\t"$2"\t"$3}'
}

# print which files are used by processes with the given name. filesp [process]
filesp() {
  lsof -c "$1" 2>/dev/null | awk '{print $2"\t"$9}'
}

# prints the list of files for the given processes (unique). filespu [process]
filespu() {
  filesp "$1" | awk 'NR > 1 {print $2}' | sort -u
}

# grep recursively and paginate
grpr() {
  ignore_options="$(printf '%s' "${DIRS_IGNORE-}" | sed 's/-x /--exclude-dir=/g')"
  grep --color=always --line-number --binary-files=without-match \
    --directories=skip --ignore-case --recursive "${ignore_options}" "$@" \
    | less -FRX
}

ind() {
  (cd -- "${1?no directory given}" && eval "${2:-}")
}

# shellcheck disable=SC2012
lt() {
  # count="${1-10}"
  # ls -Ahltr -F --color=always | tail -"${count}"
  if [ -d "$1" ]; then
    if [ "$#" -gt 1 ]; then
      (cd -- "$1" && ls -Ahltr -F --color=always | tail -n "${2:-10}")
    else
      (cd -- "$1" && ls -Ahltr -F --color=always | tail -n 10)
    fi
  else
    count=${1-10}
    ls -Ahltr -F --color=always | tail -n "${count}"
  fi
}

lw() {
  command -p -- find -L -- "${@:-.}" -mindepth 1 -maxdepth 1 | command wc -l
}

mkcd() {
  mkdir -p -- "$1" || return
  cd -- "$1" || return
}

# n | quickest note taker
n() {
  test -r "${HOME%/}"'/.n' \
    || command touch -- "${HOME%/}"'/.n' \
    && command chmod -- 600 "${HOME%/}"'/.n'
  # shellcheck disable=SC2312
  [ "$#" = 0 ] && tail ~/.n || echo "$(date +"%F %R"): $*" >>~/.n
}

nh() { nohup "$@" >/dev/null 2>&1 & }

now() {
  now="$(command -p -- date -- '+%Y%m%d%H%M%S')"
  printf '%s' "${now}"
}

pkg_config_get() {
  pkg-config --variable=pcfiledir "$1" | xargs -I {} cat {}/"$1".pc
}

sr() {
  grep --color=always "$*" --exclude-dir=".git" --exclude-dir="node_modules" \
    --exclude-dir=".nc_plugin" --ignore-case --recursive . \
    | less --no-init --raw-control-chars
}

touchf() {
  for f in "$@"; do
    mkdir -p -- "$(dirname -- "${f}")"
    touch -- "${f}"
  done
}

# shellcheck disable=SC2312
u() {
  cd "$(seq "${1:-1}" | sed 's|.*|../|' | tr -d '\n')" || return
}

# direnv
# shellcheck disable=SC2312
# command -v -- direnv >/dev/null 2>&1 && eval "$(direnv hook bash)"

# shellfish
alias shellfishreload='LC_TERMINAL=ShellFish . "${HOME%/}"'\''/.shellfishrc'\'''
if [ "${LC_TERMINAL-}" = "ShellFish" ]; then
  # shellcheck source=/dev/null
  test -e "${HOME}/.shellfishrc" && . "${HOME}/.shellfishrc"
fi

# ensure good return code
