# ~/.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=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)
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; 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


# 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


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

device_name=`hostname`;


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 "$@"
}
traceroutek(){ traceroute kam.mff.cuni.cz "$@"
}
pin8(){ ping 8.8.8.8 "$@"
}
traceroute8(){ traceroute 8.8.8.8 "$@"
}


######################### 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 & ) 
}
run(){
	$@;
}
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 "$@"
}

######################### youtube-dl
youtube() {
	youtube-dl $@ -o - | vlc -
}

######################### 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 $@)
}

# Add an "alert" alias for long running commands.  Use like so:
#   sleep 10; alert
alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'





#########################################################
######################### 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]";
			printf  ${usr:${#lastcmdStr}} | sed -e 's/* \(.*\)/(\1)/'
		else
			printf  $usr | sed -e 's/* \(.*\)/(\1)/'
		fi
	fi
	exit $lastcmd
}

######################### $ and new line
promt_NewLine=0;
promt_MakNewLine(){
	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
}
pNR()
{
	if [ $promt_NoRight -eq 0 ]; then
		promt_NoRight=1;
	else
		promt_NoRight=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" == "externalArch" ] ;
then
	promt_color_user=33
fi

if [[ "$device_name" == acid ]] || [[ "$device_name" == poppi ]]
then
	promt_color_dir=91
fi
if [[ "$device_name" == *kam* ]] || [[ "$device_name" == *cam* ]]
then
	promt_color_dir=92
fi
# 93 -> git
if [ "$device_name" == "arzen" ] ;
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

######################### 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[$ve]\e[${promt_color_dir}m$wd"
		fi
	fi
}

promt_NoRight=1
promt_right()
{
	lastcmd=$?;
	if [ "$promt_NoRight" -eq 0 ]
	then 
		printf "%*s" $(( $(tput cols) + 6 ))  "$(echo -e "\e[${promt_color_right}m[$(date +%H:%M:%S)]\015")"
	fi
	exit $lastcmd
}

######################### PS1
promt_PS1='\
\[$(promt_right)\]\
${debian_chroot:+($debian_chroot)}\
\[\033[01;${promt_color_rvalue}m\]`promt_rvalue`\
\[\033[01;${promt_color_user}m\]\u@\h\
\[\033[${promt_color_dolar}m\]:\
\001\e[${promt_color_dir}m\002$\w\
\[\033[00m\]\[\033[01;${promt_color_git}m\]`promt_parse_git_branch`\
\[\033[0m\]\
\[\033[${promt_color_dolar}m\]\
`promt_MakNewLine`\[\033[21m\]\[\033[0m\] '

PS1="$promt_PS1"

# unset color_prompt force_color_prompt

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

if [[ -z "${DISPLAY}" ]] && [[ "${XDG_VTNR}" = "1" ]]; then
  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)" "$@"
}


