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

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

######################### spawn-alacritty-cwd
PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME}:${PWD}\007"'
if [[ "$LC_CD" != "" ]];
then
	cd "$LC_CD";
	export -n LC_CD
fi

########################################################################
######################### BASIC DEFAULT CONFIG #########################
########################################################################

######################### Local bin
export PATH=$PATH:~/bin
#unalias -a

######################### history files
# 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=10000
HISTFILESIZE=20000


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

# 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


##########################################################################
######################### GLOBAL HELPER FUNCTONS #########################
##########################################################################

device_name()
{
	tmp="\h";
	echo ${tmp@P};
}
device_name=`device_name`;


char() {
  [ "$1" -lt 256 ] || return 1
  printf "\\$(printf '%03o' "$1")"
}


###############################################################################
######################### ALIASES AND PROGRAMS CONFIG #########################
###############################################################################

#test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"

real_ls=$(which ls)
ls(){
	$real_ls --color=auto "$@"
}

######################### grep
real_grep="$(which grep)"
grep(){
	$real_grep --color=auto "$@"
}
real_fgrep="$(which fgrep)"
fgrep(){
	$real_fgrep --color=auto "$@"
}
real_egrep="$(which egrep)"
egrep(){
	$real_egrep --color=auto "$@"
}

######################### ls
unalias ll 2>/dev/null
unalias la 2>/dev/null
unalias l 2>/dev/null
ll(){
	ls -alF "$@"
}
la(){
	ls -A "$@"
}
l(){
	ls -CF "$@"
}

######################### vim
if which nvim >/dev/null 2>/dev/null
then
	export EDITOR=nvim
	export MANPAGER='nvim +Man!'
else
	export EDITOR=vim
fi
e(){
	$EDITOR "$@"
}
vi(){
	e "$@"
}
view(){
	e -R "$@"
}

######################### ping, traceroute
pink(){
	ping kam.mff.cuni.cz "$@"
}
pink4(){
	ping 195.113.20.16 "$@"
}
pink6(){
	ping 2001:718:1e03:801::10 "$@"
}
traceroutek(){ traceroute kam.mff.cuni.cz "$@"
}
pin8(){ ping 8.8.8.8 "$@"
}
traceroute8(){ traceroute 8.8.8.8 "$@"
}
pinb(){
	ping blatto.eu "$@"
}
pinb4(){
	ping 95.85.217.30 "$@"
}
pinb6(){
	ping 2a01:510:d504:75a0::1 "$@"
}


######################### mkdir, cd
mcd(){
	mkdir -p "$1"; cd "$1"
}
mkdircd(){
	mkdir "$1"; cd "$1"
}

######################## Open on background
BG(){
	( "$@" 1>/dev/null 2>/dev/null & ) 
}

gopen(){
	( xdg-open "$@" 2>/dev/null 1>/dev/null & ) 
}
g(){
	( xdg-open "$@" 2>/dev/null 1>/dev/null & ) 
}
zath(){
	for i in "$@"
	do
		zathura "$i" & sleep 0.2
	done
}
zath1(){
	for i in "$@"
	do
		zathura "$i" --page=1 & sleep 0.2
	done
}

######################### Separators
promt(){
	echo -n "${PS1@P}" | tr -d `char 1``char 2`
}
bashLine(){
	promt
	echo "$@"
	"$@"
}
sepLine(){
	s=$(printf "%-`stty size | cut -d ' ' -f 2`s" " ");echo -e "\e[30;48;5;82m${s// / }\e[0m"
}

######################### remove, coppy, move
real_rm="$(which rm)"
rmHARD(){
	$real_rm "$@"
}
rm(){
	trash  "$@"
}
real_cp="$(which cp)"
cp(){
	$real_cp -i "$@"
}
real_mv="$(which mv)"
mv(){
	$real_mv -i "$@"
}
mňau(){
	cat "$@"
}
rs(){
	rsync --recursive --info=progress2 --info=name1 --sparse  --stats  "$@"
}
rsa(){
	rs -at "$@"
}

######################### git
gic(){
	git commit "$@"
}
gica(){
	git commit --amend "$@"
}
gis(){
	git status "$@"
}
gig(){ 
	git log --oneline --graph "$@"
}
gil(){
	git log --max-count=1 "$@"
}
gia(){
	git add "$@"
}
giac(){
	git add "$@"; git commit;
}
giaac(){
	git add . "$@"; git commit;
}
giaca(){
	git add "$@"; git commit --amend;
}
giaaca(){
	git add . "$@"; git commit --amend;
}
gip(){
	git pull "$@"; git push "$@";
}
gipma(){
	b=$1
	[[ "$b" == "" ]] && b="$(git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/')"
	git remote | while read r ; do echo -e "\e[91;1m PULL MEERGE $r $b\e[0m"; git pull $r $b --no-rebase ; done
	git remote | while read r ; do echo -e "\e[91;1m PUSH $r $b\e[0m"; git push $r $b ; done
}
gipa() {
	b=$1
	[[ "$b" == "" ]] && b="$(git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/')"
	git remote | while read r ; do echo -e "\e[91;1m PULL $r $b\e[0m"; git pull $r $b ; done
	git remote | while read r ; do echo -e "\e[91;1m PUSH $r $b\e[0m"; git push $r $b ; done
}
gir(){
	git rebase $@
}
giri(){
	git rebase -i $@
}
girc(){
	git rebase --continue $@
}
 
######################### systemctl
sys(){
	root systemctl  "$@"
}
syss(){
	root systemctl start "$@"
}
syse(){
	root systemctl stop "$@"
}
sysp(){
	root systemctl status "$@"
}

######################### movingssh
ms(){
	movingssh "$@"
}
complete -F _movingssh ms

######################### gpg
bye(){
	gpg-connect-agent reloadagent /bye
}

######################### neofetch
neopeč(){
	neofetch
}

######################### ip

ipa(){
	ip -br -c a
}

######################### root
please(){
	root $(fc -ln -1)
}

######################### python
p(){
	bpython "$@"
}
p3(){
	python3 "$@"
}
pe(){
	p="$PS1"
	. "${1:-.}"/venv/bin/activate
	PS1="$p"
}
pde(){
	deactivate
}

####################### make
makej(){
	make -j8 "$@"
}
makeme(){
	make "$@" "$(cat /etc/hostname)"
}



d(){
	BG ~/.config/alacritty/spawn-alacritty-cwd
}

cwd(){
	cd $(wd $@)
}

mcwd(){
	mcd $(wd $@)
}



#########################################################
######################### PROMT #########################
#########################################################

######################### git
promt_NoGit=0
promt_parse_git_branch() {
	if [ $promt_NoGit -eq 0 ]; then 
		promt_git_branch="$(git branch 2>&1)"
		if ! [[ "$promt_git_branch" == *"fatal: not a git repository"* ]]
		then
			if [[ "$promt_git_branch" == *"fatal: unsafe repository"* ]]
			then
				echo "[S]"
			else
				promt_git_branch=$(echo "$promt_git_branch" |sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/')
				if [[ "$promt_git_branch" == '('*')' ]]
				then
					echo "$promt_git_branch"
				else
					echo "[E]"
				fi
			fi
		fi
	else
		echo "[?]"
	fi
}

######################### return value and user
promt_rvalue() {
	lastcmd=$?;
	if [ $lastcmd -ne 0 ]; then 
		echo "[$lastcmd]";
	fi
	exit $lastcmd
}
promt_NoUser=0
promt_usrCut(){
	lastcmd=$?
	usr="\u@\h"
	usr="${usr@P}"
	if [ $promt_NoUser -eq 0 ]; then 
		if [ $lastcmd -ne 0 ]; then 
			lastcmdStr="[$lastcmd]";
			echo "${usr:${#lastcmdStr}}"
		else
			echo "$usr"
		fi
	fi
	exit $lastcmd
}

######################### $ and new line
promt_NewLine=0;
promt_MakeNewLine(){
	if [ $promt_NewLine -ne 0 ]; then 
		printf  '\n$' #| sed -e 's/* \(.*\)/(\1)/'
	else
		printf  '$' #| sed -e 's/* \(.*\)/(\1)/'
	fi
}

######################### config functions
pNL()
{
	if [ $promt_NewLine -eq 0 ]; then
		promt_NewLine=1;
	else
		promt_NewLine=0;
	fi
}
pNN()
{
	if [ $promt_NoUser -eq 0 ]; then
		promt_NoUser=1;
	else
		promt_NoUser=0;
	fi
}
pG()
{
	if [ $promt_NoGit -eq 0 ]; then
		promt_NoGit=1;
	else
		promt_NoGit=0;
	fi
}

nm()
{
	neomutt -f"notmuch://?query=$1" ; offlineimap-run all
}
nmt()
{
	neomutt -f"notmuch://?query=thread:{$1}" ; offlineimap-run all
}
nmi()
{
	nm "tag:unread or tag:flagged"
}
nmat()
{
	notmuch search --output=tags '*'
}



######################### default colors
promt_color_rvalue=91
promt_color_user=32
promt_color_dir=96
promt_color_git=93
promt_color_venv=93
promt_color_dolar=39
promt_color_right=32


######################### configuration by devices
if [[ "$device_name" == arch ]] || [[ "$device_name" == arzen ]]
then
	promt_color_dir=91
fi
if [[ "$device_name" == *kam* ]] || [[ "$device_name" == *cam* ]]
then
	promt_color_dir=92
fi
# 93 -> git
if [ "$device_name" == hopik ] ;
then
	promt_color_dir=94
fi
if [[ "$device_name" == rpi* ]]
then
	promt_color_dir=95
fi


######################### configuration by connection types
if [ "$SSH_CONNECTION" != "" ];
then 
	if [ "$LD_SSHTYPE" = "localhost" ] || [ "$LC_SSHTYPE" = "localhost" ]
	then
		true
	elif [ "$LD_SSHTYPE" = "second" ] || [ "$LC_SSHTYPE" = "second" ]
	then 
		promt_color_user=33
	elif [ "$LD_SSHTYPE" = "local" ] || [ "$LC_SSHTYPE" = "local" ]
	then 
		promt_color_user=96
	else
		promt_color_rvalue=32
		promt_color_user=91
	fi
fi
#
######################### non-native instalations
if [ "$device_name" == "externalArch" ] || [ -e /etc/is_virtual ];
then
	promt_color_user=33
fi


######################### phone: no device name
if [ "$SSH_CONNECTION" == "" ]
then
	if [ "$device_name" = "localhost" ]
	then
		pNN
	fi
fi

if [ "$ISBREAKEBLE" = "1" ] ;
then
	promt_color_user=95
fi

######################### configuration by user (root)
if [ "$USER" == "root" ];
then 
	promt_color_dolar="91;1"
fi


promt_pwd(){
	wd="\w"
	wd="${wd@P}"
	if [[ "$VIRTUAL_ENV" == "" ]]
	then
		echo -e "\001\e[${promt_color_dir}m\002$wd"
	else
		ve="${VIRTUAL_ENV%/venv}"
		[[ "$ve" =~ ^"$HOME"(/|$) ]] && ve="~${ve#$HOME}"
		if [[ "$wd" =~ ^"$ve" ]]
		then
			echo -ne "\001\e[${promt_color_dir}m\002[\001\e[${promt_color_venv}m\002$ve\001\e[${promt_color_dir}m\002].${wd#$ve}"
		else
			echo -ne "\001\e[${promt_color_venv}m\002[$ve]\001\e[${promt_color_dir}m\002$wd"
		fi
	fi
}

######################### PS1
promt_PS1='\
\[\e[01;${promt_color_rvalue}m\]$(promt_rvalue)\
\[\e[01;${promt_color_user}m\]$(promt_usrCut)\
\[\e[${promt_color_dolar}m\]:\
$(promt_pwd)\
\[\e[00m\]\[\e[01;${promt_color_git}m\]$(promt_parse_git_branch)\
\[\e[0m\]\
\[\e[${promt_color_dolar}m\]\
$(promt_MakeNewLine)\[\e[21m\]\[\e[0m\] '

PS1="$promt_PS1"

# unset color_prompt force_color_prompt

###############################################################
######################### AUTO STARTX #########################
###############################################################

if [[ -z "${DISPLAY}" ]] && [[ "${XDG_VTNR}" = "1" ]]; then
  exec startx
fi


####################################################################
######################### BASHRC DIRECTORY #########################
####################################################################

for i in ~/.config/bash/*
do
	  . $i
done 2>/dev/null
for i in ~/bin/bashrc/*
do
	  . $i
done 2>/dev/null

aux()
{
	if [[ "$(pwd)" == /aux/* ]]
	then
		cwd 0 home
	else
		cwd 0 aux
	fi
}

unset MAILCHECK

lpl()
{
	lp -o Duplex=DuplexTumble -o XRFold=BiFoldStaple -o XROutputMode=HighResolution "$@"
}
lp1l()
{
	lp -o Duplex=DuplexTumble -o XROutputMode=HighResolution "$@"
}


h(){
	xdo hide "$WINDOWID";
	"$@"
	r=$?
	xdo show "$WINDOWID"
	return $r
}

x()
{
	h "$(which x)" "$@"
}


bind -x '"\C-o": ranger-select files ""'
bind -x '"\eo": ranger-select dir "/"'

ranger-select() {
	local F=$(mktemp)
	ranger --choose$1=$F
	if [ -s $F ] ; then
		local SEL="$(<$F sed '/[^0-9A-Za-z._/-]/{s/^/"/; s/$/"/;}' | tr '\n' ' ')"
		if [ "${SEL:${#SEL}-1}" != " " ] ; then
			SEL="$SEL$2 "
		fi
		READLINE_LINE="${READLINE_LINE:0:$READLINE_POINT}$SEL${READLINE_LINE:$READLINE_POINT}"
		READLINE_POINT=$(($READLINE_POINT + ${#SEL}))
	fi
	rm -f $F
}

ranger-cd() {
	local F=$(mktemp)
	ranger --choosedir=$F
	if [ -s $F ] ; then
		if [ "$(cat -- $F)" != "$(echo -n `pwd`)" ] ; then
			cd -- "$(cat $F)"
		fi
	fi
	rm -f $F
}