#!/bin/bash

# $- meaning see https://stackoverflow.com/questions/42757236/what-does-mean-in-bash
# If not running interactively, don't do anything
#[[ $- != *i* ]] && return
# https://github.com/westscz/.dotfiles/blob/master/system/bashrc
case $- in
	*i*) ;;
	*) return;;
esac

. /usr/share/fzf/completion.bash
. /usr/share/fzf/key-bindings.bash
. /usr/share/bash-complete-alias/complete_alias

# default PS1
#PS1='[\u@\h \W]\$ '

# deprecated
# 0: not bold, 91: bright red
# \e[m act like \e[0m, means reset so commands after it will not be colored 
# https://en.wikipedia.org/wiki/ANSI_escape_code#3-bit_and_4-bit
# need \[ and \] around color codes so bash ignore color codes when calculating line wraps?
# https://www.cyberciti.biz/faq/bash-shell-change-the-color-of-my-shell-prompt-under-linux-or-unix/#:~:text=you%20also%20need%20to%20put%20%5C%5B%20and%20%5C%5D%20around%20any%20color%20codes%20so%20that%20bash%20does%20not%20take%20them%20into%20account%20when%20calculating%20line%20wraps.
#PS1='\[\e[0;91m\][\u@\h \W]\$ \[\e[0m\]'
# \033 can be used for dash printf, but \e can't? not sure why
#PS1='\[\033[0;91m\][\u@\h \W]\$ \[\033[0m\]'

# tput is better for different terminals? 
# but also need \[ and \] around color code for PS1! but seems no need for printf in script? why?
# setaf and sgr0 see `man terminfo`, also it seems can have 256 different colors
PS1="\[$(tput setaf 1)\][\u@\h \W]\$ \[$(tput sgr0)\]"

# https://github.com/LukeSmithxyz/voidrice/blob/master/.config/shell/aliasrc
for cmd in hardcode-fixer ventoy units_cur fbgrab powertop nft rpi-imager fdisk dmesg; do
	alias $cmd="sudo $cmd"
done
for cmd in pacdiff visudo; do
	alias $cmd="sudo -E $cmd"
done
for cmd in loop o 'watch -c'; do
	alias ${cmd%% *}="$cmd "
done
unset cmd

# note: the following code pipe to while read will not work, because pipe create subshell
#git -C "$HOME/programs/config_local_arch" branch | awk '{print ($1=="*")?$2:$1}' | grep -v master | while read -r branch; do
# `man bash`: "Each command in a multi-command pipeline, where pipes are created, is executed in a subshell, which is a separate process."
# https://stackoverflow.com/questions/56327528/bash-aliases-set-in-while-loop-not-persisting
# can be tested via $BASHPID, note $$ will not work, because $$ does not show subshell pid
# another way is: echo "$(exec sh -c 'echo "$PPID"')"
# `man bash`:
# > BASHPIP Expands to the process ID of the current bash process. This differs from $$ under certain circumstances, such as subshells that  do not  require bash to be re-initialized.
# > $ Expands to the process ID of the shell. In a subshell, it expands to the process ID of the current shell, not the subshell.
# https://unix.stackexchange.com/questions/484442/how-can-i-get-the-pid-of-a-subshell
for branch in $(git -C "$HOME/programs/config_local_arch" branch | awk '{print ($1=="*")?$2:$1}' | grep -v master); do
	case "$branch" in
		master|studio|pp) ;;
		*) alias "s$branch"="ssh $branch";;
	esac
done
unset branch

# different name
alias a=alarm
# /dev/ttyACM0 can be in config file, or as environmantal variable, see /usr/share/doc/adafruit-ampy/README.md
#alias ap='ampy -p /dev/ttyACM0'
alias b='lsblk -o NAME,FSTYPE,FSVER,LABEL,UUID,FSAVAIL,FSUSED,FSUSE%,MOUNTPOINTS'
alias c=cfg
#alias cr=curl
alias cri='curl -Is'
alias crig='curl -Is www.google.com'
alias d='sdcv --color'
alias e='"$PAGER"'
# https://superuser.com/a/1202867
alias fdu="find . -maxdepth 1 -execdir du -sh '{}' \+ | sort -h"
alias g=git
alias gcd='git clone --depth=1'
alias gr='grep --color=auto -i'
alias grr='grep --color=auto -iIR'
alias h=htop
alias i=nsxiv
alias j=journalctl
alias l='ls --color=auto -A --group-directories-first'
alias ll='ls --color=auto -lAh --group-directories-first'
#alias lo=loop
alias lop='loop ping'
alias lopd='loop ping 9.9.9.9'
alias m=man
alias p=pacman
alias pt=pactree
alias pu=paru
alias qre='qrencode -t utf8i -m 1'
alias r='rem -cu+2 -@'
# https://askubuntu.com/a/22043
alias s='sudo '
alias sa='ssh-add -l || ssh-add'
alias se='sudo -E '
alias sp='ssh pp'
alias spd='speedtest; librespeed-cli'
alias sst='ssh studio'
# \" to consider $HOME contain space, need \ else " will be expanded locally, need \$ else $HOME will expand locally
# can test with: alias mytest='ssh studio for i in \"\$SSH_CONNECTION\"\; do echo \$i\; echo a\; done'
alias sstm='ssh -t -- studio mpra -c \"\$HOME/programs/repos/fly/any/fsh-git\"'
# from `man remind`: "Note that you can omit the reminder type, in which case it defaults to MSG"
# can test this mess with `alias tt='echo "\$haha \"lala\""'`
alias sun='printf "set \$Longitude \"-121.89\"\nset \$Latitude \"37.34\"\n[sunrise()] sunrise\n[sunset()] sunset" | remind -n -'
# another way:
# can test this mess with `alias tt="echo '\$haha \"lala\"'"`
#alias sun="printf 'set \$Longitude \"-121.89\"\nset \$Latitude \"37.34\"\n[sunrise()] sunrise\n[sunset()] sunset' | remind -n -"
alias sv=sudoedit
alias y=systemctl
alias yd='systemctl list-dependencies --all'
alias ydr='systemctl list-dependencies --all --reverse'
alias ye='systemctl list-unit-files --state=enabled'
alias ys='systemctl status'
alias yu='systemctl --user'
alias yue='systemctl --user list-unit-files --state=enabled'
alias yus='systemctl --user status'
alias v='"$EDITOR"'
alias va='"$EDITOR" "$XDG_DOCUMENTS_DIR/notes/computer/arch_install.md"'
alias vc='"$EDITOR" "$XDG_DOCUMENTS_DIR/notes/computer/cli_notes.md"'
alias vd='vidir'
alias vd2='vidir2 --linktargets'
alias vq='"$EDITOR" "$XDG_DOCUMENTS_DIR/notes/others/questions_ideas_tips.md"'
alias vn='"$EDITOR" "$(find "$XDG_DOCUMENTS_DIR/notes" -mindepth 1 -path "*/\.git" -prune -o -type f -print | fzf)"'
alias vni='"$EDITOR" -ni NONE'
alias vr='"$EDITOR" "$DOTREMINDERS"'
alias vrc='"$EDITOR" +e\ \$MYVIMRC'
alias vrm='"$EDITOR" "$XDG_DOCUMENTS_DIR/notes/others/recurring_maintenance.md"'
alias vt='"$EDITOR" "$XDG_DOCUMENTS_DIR/notes/others/tmp_mobile_notes.md"'
alias xmr='monero-wallet-cli --config-file="$HOME/.bitmonero/monero-wallet-cli.conf"'
alias xmrds='monerod status; monerod print_net_stats'
alias za='zoxide add'
#alias zq='zoxide query'
#alias zqi='zoxide query -i'

# same name
alias absolutely-proprietary='echo n | absolutely-proprietary -f'
alias alsamixer='alsamixer -V all'
# I can't find a quick and easy way to temperory disable cloc config file except to change config file. Using an alias can disable --vcs with just \cloc.
alias cloc='cloc --vcs auto'
alias diff='diff --color=auto'
alias glmark2='glmark2 --fullscreen --annotate'
alias grep='grep --color=auto'
#alias info='info --vi-keys'
alias ls='ls --color=auto'
alias radeontop='radeontop -c'
alias rem='rem -@'
alias remind='remind -@'
alias rm='rm -I'
alias sdcv='sdcv --color'
alias shellcheck='shellcheck -x'
alias tree='tree -aC -I .git | "$PAGER"'
alias uname='uname -a'
alias vkmark='vkmark --fullscreen'

# deprecated
# all green color, no auto turn off color when pipe to nvim
#alias pactree='pactree -c'

#eval "$(zoxide init posix --hook prompt --no-aliases)"
# if no --no-aliases, when tab complete a dir name contain spaces, bash will not escape spaces, don't know why, maybe bug?
eval "$(zoxide init bash --no-aliases)"

z () {
	if  __zoxide_z "$@"; then
		l
		echo "$PWD"
	fi
}

zi () {
	if __zoxide_zi "$@"; then
		l
		echo "$PWD"
	fi
}

# steal from fzf: https://github.com/junegunn/fzf/blob/master/shell/key-bindings.bash
# READLINE_LINE and READLINE_POINT see `man bash`
zqi_key () {
	# fzf uses printf '%q' to escape output, but attention %q is not POSIX
	# well we use bash here so whatever
	selected="$(printf '%q' "$(zoxide query -i)")"
	# if don't want to use bash builtin printf:
	#selected=$(/usr/bin/printf '%q' "$(zoxide query -i)")
	# no "''" if select nothing
	if ! [ "$selected" = "''" ]; then
	# another way:
	#selected=$(zoxide query -i | tr '\n' '\0' | xargs -0 printf '%q')
	#if [ "$selected" ]; then
		READLINE_LINE="${READLINE_LINE:0:$READLINE_POINT}$selected ${READLINE_LINE:$READLINE_POINT}"
		READLINE_POINT=$((READLINE_POINT+${#selected}+1))
	fi
}
bind -m vi-command -x '"\C-o":zqi_key'
bind -m vi-insert -x '"\C-o":zqi_key'

# more about bash completion see https://unix.stackexchange.com/a/529357/459013
complete -c wh
# tldr-sh-client readme 
complete -W "$(tldr 2>/dev/null -l -p all)" tldr
# copy from `complete -p drill`
# https://github.com/scop/bash-completion/blob/e209afb2d0c96ee6bfe83da8b2742a8f8e88d372/bash_completion#L2404-L2420
# The url has the code of _comp_complete_known_hosts function, it says it is deprecated as a helper funtion and I should use _comp_compgen_known_hosts instead? Does my use count as helper function? I don't know how to use _comp_compgen_known_hosts. And _comp_complete_known_hosts works, so whatever.
complete -F _comp_complete_known_hosts pa
# https://unix.stackexchange.com/questions/216748/how-to-re-use-existing-completion-with-recent-bash-completion
_completion_loader info
eval "$(complete -p info | sed 's/\(.*\)info$/\1vinfo/')"
_completion_loader git
eval "$(complete -p git | sed 's/\(.*\)git$/\1cfg/')"
_completion_loader pass
eval "$(complete -p pass | sed 's/\(.*\)pass$/\1prp/')"
# complete-alias readme
complete -F _complete_alias "${!BASH_ALIASES[@]}"