#
# ~/.bashrc
#

##########################
#Commands
##########################

#search files in current dir and subdirs using fzf
alias search='find . -type f | fzf -m'

#show battery % on laptop
alias batt="echo 'BAT 1' ; upower -i /org/freedesktop/UPower/devices/battery_BAT0 | grep 'time to empty\|percentage:' ; echo 'BAT 2' ; upower -i /org/freedesktop/UPower/devices/battery_BAT1 | grep 'time to empty:\|percentage:'"
#fullcharges batteries one time instead of 40% 
alias fullcharge="sudo tlp fullcharge BAT0 ; sudo tlp fullcharge BAT1"

#display the weather
alias wea="curl wttr.in/NewYork?u"
#display btc prices
alias btc="curl -s rate.sx/btc > test.txt ; echo 'BTC Price:' ; grep --color=never  avg: test.txt; rm test.txt"

#reboot into windows for dual-boot systems, set to correct index
alias win='sudo grub-reboot 2 && sudo reboot now'

#sends a wol packet to my desktop so I can wake it if sleeping and ssh into it or use rustdesk to control it
alias lianli-wol='wol --verbose 04:7C:16:5B:DC:44'

#display help file for these commands
alias hlp='cat ~/.help | more'

#delete exif data from given files, warning overwrites original files
alias delex='exiftool -overwrite_original -all= '

#more things
alias cp="cp -i"                          # confirm before overwriting something
alias df='df -h'                          # human-readable sizes
alias free='free -m'                      # show sizes in MB
alias more=less
alias igrep='grep -i'


##########################
#Directory Commands
##########################

alias ..='cd ..'
alias ...='cd ../..'
alias ....='cd ../../..'
alias ll='ls -lh --group-directories-first' 
alias lll='ls -lah --group-directories-first' #makes more sense to set this to lla instead of lll which I have done since the video
alias lsa='ls -ah --group-directories-first'
alias l.='ls -d .* --color=auto --group-directories-first' 
alias list='ls -halt | head'


##########################
#Directory Shortcuts
##########################

alias movies='cd /shared/media/movies/'
alias tv='cd /shared/media/tv'
alias public='cd /shared/public'
alias common='cd /shared/common'


##########################
#Software/Updates
##########################

alias update='sudo pacman -Syu'
alias yolo='yes | update'
alias fps='flatpak search --columns=name:f,version:f,description:f,application:f'


##########################
#Terminal Options
##########################

#set prompt
PROMPT_COMMAND="echo -ne \"\033]0;$1 local\007\""

#set default editor
export VISUAL="micro"

#history settings
export HISTSIZE=1000
export HISTCONTROL=ignoredups
shopt -s histappend #enable history appending instead of overwriting.

#enable tab completion for sudo
complete -cf sudo

#checks if window size changed
shopt -s checkwinsize

#expand aliases in non-interactive shells
shopt -s expand_aliases

#completes / with tab on the end of symlinked dirs
bind 'set mark-symlinked-directories on'


##########################
#Set custom window title
##########################
function title() {
  if [[ -z "$ORIG" ]]; then
    ORIG=$PS1
  fi
  TITLE="\[\e]2;$*\a\]"
  PS1=${ORIG}${TITLE}
}

[[ $- != *i* ]] && return


##########################
#Fuzzy Finder
##########################

#### ctrl+r - search bash history
bind '"\C-r": "\C-x1\e^\er"'
bind -x '"\C-x1": __fzf_history';

__fzf_history ()
{
__ehc $(history | fzf --tac --tiebreak=index | perl -ne 'm/^\s*([0-9]+)/ and print "!$1"')
}

__ehc()
{
if
        [[ -n $1 ]]
then
        bind '"\er": redraw-current-line'
        bind '"\e^": magic-space'
        READLINE_LINE=${READLINE_LINE:+${READLINE_LINE:0:READLINE_POINT}}${1}${READLINE_LINE:+${READLINE_LINE:READLINE_POINT}}
        READLINE_POINT=$(( READLINE_POINT + ${#1} ))
else
        bind '"\er":'
        bind '"\e^":'
fi
}

#### fkill - kill process with fzf
fkill() {
    local pid 
    if [ "$UID" != "0" ]; then
        pid=$(ps -f -u $UID | sed 1d | fzf -m | awk '{print $2}')
    else
        pid=$(ps -ef | sed 1d | fzf -m | awk '{print $2}')
    fi  

    if [ "x$pid" != "x" ]
    then
        echo $pid | xargs kill -${1:-9}
    fi  
}

#### fe - Open the selected file with the default editor
#   - Bypass fuzzy finder if there's only one match (--select-1)
#   - Exit if there's no match (--exit-0)
fe() {
  IFS=$'\n' files=($(fzf-tmux --query="$1" --multi --select-1 --exit-0))
  [[ -n "$files" ]] && micro  "${files[@]}"
}

#### fdd - change dir
fdd() {
  local dir
  dir=$(find ${1:-.} -path '*/\.*' -prune \
                  -o -type d -print 2> /dev/null | fzf +m) &&
  cd "$dir"
}

#### fd - change dir, list subdirs
fd() {
  DIR=`find * -maxdepth 0 -type d -print 2> /dev/null | fzf-tmux` \
    && cd "$DIR" && fd
}

#### fda - change dir, including hidden directories
fda() {
  local dir
  dir=$(find ${1:-.} -type d 2> /dev/null | fzf +m) && cd "$dir"
}

##########################
#Colors
##########################

# Set colorful PS1 only on colorful terminals.
# dircolors --print-database uses its own built-in database
# instead of using /etc/DIR_COLORS.  Try to use the external file
# first to take advantage of user additions.  Use internal bash
# globbing instead of external grep binary.
safe_term=${TERM//[^[:alnum:]]/?}   # sanitize TERM
match_lhs=""
[[ -f ~/.dir_colors   ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"
[[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"
[[ -z ${match_lhs}    ]] \
	&& type -P dircolors >/dev/null \
	&& match_lhs=$(dircolors --print-database)
[[ $'\n'${match_lhs} == *$'\n'"TERM "${safe_term}* ]] && use_color=true

if ${use_color} ; then
	# Enable colors for ls, etc.  Prefer ~/.dir_colors #64489
	if type -P dircolors >/dev/null ; then
		if [[ -f ~/.dir_colors ]] ; then
			eval $(dircolors -b ~/.dir_colors)
		elif [[ -f /etc/DIR_COLORS ]] ; then
			eval $(dircolors -b /etc/DIR_COLORS)
		fi
	fi

	if [[ ${EUID} == 0 ]] ; then
		PS1='\[\033[01;31m\][\h\[\033[01;36m\] \W\[\033[01;31m\]]\$\[\033[00m\] '
	else
		PS1='\[\033[01;32m\][\u@\h\[\033[01;37m\] \W\[\033[01;32m\]]\$\[\033[00m\] '
	fi

	alias ls='ls --color=auto'
	alias grep='grep --colour=auto'
	alias egrep='egrep --colour=auto'
	alias fgrep='fgrep --colour=auto'
else
	if [[ ${EUID} == 0 ]] ; then
		# show root@ when we don't have colors
		PS1='\u@\h \W \$ '
	else
		PS1='\u@\h \w \$ '
	fi
fi

unset use_color safe_term match_lhs sh


##########################
# # ex - archive extractor script
# # usage: extract <file>
##########################
extract ()
{
  if [ -f $1 ] ; then
    case $1 in
      *.tar.bz2)   tar xjf $1   ;;
      *.tar.gz)    tar xzf $1   ;;
      *.bz2)       bunzip2 $1   ;;
      *.rar)       unrar x $1     ;;
      *.gz)        gunzip $1    ;;
      *.tar)       tar xf $1    ;;
      *.tbz2)      tar xjf $1   ;;
      *.tgz)       tar xzf $1   ;;
      *.zip)       unzip $1     ;;
      *.Z)         uncompress $1;;
      *.7z)        7z x $1      ;;
      *)           echo "'$1' cannot be extracted via extract()" ;;
    esac
  else
    echo "'$1' is not a valid file"
  fi
} 

##########################
#Other adds below
##########################

