#!/usr/bin/env sh
#
# aliases and similar functions which can be used by all shells (supporting
# them).

# aliases
alias ws="cd ~/workspace && ls -ltr"
alias jp='cd ~/workspace/jupyter && ls -ltr'
alias jpa='cd ~/workspace/jupyter/admin && ls -ltr'
alias dot='cd ~/workspace/dotfiles'
alias hub='jupyterhub'
alias octave='octave-cli'
alias bel='tput bel'

alias gs='git status'
alias gsv='git status --verbose'
alias gpo='git push origin'
alias gu='git pull upstream'
alias gb="git for-each-ref --sort='-authordate:iso8601' --format=' %(authordate:relative)%09%(refname:short)' refs/heads | tail -r"
alias gd='git diff'
alias ga='git add'
alias gc='git commit --verbose'
alias gr='git remote -v'
alias gprb='git pull --rebase'
alias gnvm="git reset --soft HEAD~1"

alias search="git --no-pager grep -i -n"
alias searchsensitive="git --no-pager grep -n"

alias ubuntu='docker run -it -e GRANT_SUDO=yes --user root jupyter/minimal-notebook bash'
export PROMPT_COMMAND='echo'

# shortcuts for often used programs.
alias b=bat
alias c=clear
alias d=cd
#alias e=elinks
alias g=git
#alias h=htop
alias l=ls
#alias p=less # p for pager
#alias s=ssh
#alias t=tig
alias v=vim
alias x=exit
# shortcuts for a little less used programs.
#alias ga='git annex'
alias gr=grep
alias gri='grep -i'
alias grr='grep -r'
alias grri='grep -ri'
#alias mu=mutt
#alias rs=reset # like git's reset alias
#alias sa=ssh-add
#alias ta=task
#alias te=tree
#alias ti=timew

# systemd ... (sc is provided as shell script for better completion); redirect
# stderr because my color-stderr hack breaks systemd's terminal detection.
#jc() {
#  journalctl "$@" 2>&1
#}
#lc() {
#  loginctl "$@" 2>&1
#}

unalias mv cp 2>/dev/null
# Ask for confirmation before overwriting files. Especially useful when moving
# to a different directory. No alias for `rm` because I specify the files to
# remove directly, so I know what will happen.
alias mv='mv -i'

# Make sure there is no alias named ls as it causes problems with the
# following ls function on (at least) bash 4.0.35.
unalias ls 2>/dev/null
# Improved ls which displays the files in columns (-C), visualizes
# directories, links and other special files (-F), uses human file sizes (-h)
# and pages everything through less.
#
# If available use GNU ls with colorized output. If it isn't available try
# normal ls which needs CLICOLOR_FORCE so it displays colors when used with a
# pager. If none work no colors are used.
#
# See `setup.sh` for details. LS_* are replaced with the appropriate values
# when this file is generated.
ls() {
    LS_ARGS -C -F -h "$@" 2>&1 | less -S
}

unalias ll lt la lal lat 2>/dev/null
# List the files in list format with access rights, etc.
alias ll='ls -l'
# List the files sorted by last modification date.
alias lt='ls -l -t'
# List all files.
alias la='ls -a'
# List all files in list format with access rights, etc.
alias lal='ls -al'
# List all files sorted by last modification date.
alias lat='ls -al -t'

# make going up directories simple.
alias ..='cd ..'
alias ...='cd ../..'
alias ....='cd ../../..'
alias .....='cd ../../../..'

# automatically use unified diffs.
alias diff='diff -u'

# COLUMN is set to `| column -t` if it's available, empty otherwise.

# display all files (-s), use human readable sizes (-h) and display the
# complete size (-c).
alias du='du -shc'
# Use human readable sizes and format it nicely, thanks to climagic
# (http://twitter.com/climagic/status/49623386762129408).
df() {
    command df -hP "$@" COLUMN
}

# highlight matched strings. doesnt work with a pager!
alias grep='grep --color=auto'

# pipe output through less.
tree() {
    command tree -C "$@" | less -S
}

# Groff versions >= 1.23 don't support LESS_TERMCAP_* to color man pages, set
# GROFF_NO_SGR as workaround. Also set LANG to C so that hyphens are not
# replaced with unicode making it impossible to search for options containg
# "-" or "--" in many man pages (these are errors in the man page but very
# common; Debian reverted this behavior in 1.23.0-3 but other distributions
# might not).
man() {
    GROFF_NO_SGR=1 LANG=C command man "$@"
}

# Better viewer for info pages .. just pipe everything into less.
info() {
    command info "$@" 2>/dev/null | less
}

# Using su (or sudo) as root to a less privileged user might allow the other
# user to run arbitrary commands as root. See also Debian bugs #628843 and
# #657784.
if test "`id -u`" -eq 0; then
    su() {
        echo 'never su as root' >&2
        return 1
    }
fi

# Use short `ip` output per default.
alias ip='ip -brief -color=auto'

# Calendar with traditional output (-b), weeks starting on Monday (-M), week
# numbers (-w) and the previous, current and next month (-3)
alias cal='ncal -b -M -w -3'

# Group volumes on mdadm devices instead of displaying them multiple times
alias lsblk='lsblk --merge'


# vim: ft=sh:sw=2:ts=2:sts=2:fdm=marker:fdl=0:noml:

# Delete superfluous files recursively
alias del.pyc='find . -type f -name "*.pyc" -delete'
alias del.tilde='find . -type f -name "*~" -delete'
alias del.clean="del.pyc && del.tilde"

################################################################################

# add an "alert" alias for long running commands
# usage: 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$//'\'')"'

################################################################################

###########################
### Aliases / Functions ###
###########################
# Aliases are in this .zshenv file to make them work in VIM's non-interactive shell

VIM_EDITOR=nvim
MAIN_EDITOR=$VIM_EDITOR

# Unix
alias ls='ls -G'
alias ll='ls -lh'
alias la='ls -A'
alias lla='ll -A'
alias lld='ll -d'
alias llrt='ll -rt'
alias llart='lla -rt'
alias rm='rm'
alias rmrf='rm -rf'
rmrf.() {
  local dir=$(pwd)
  if [[ $dir == ~/c/* ]]; then
    cd ..
    rm -rf $dir
  else
    echo 'ERROR: this command only works in ~/c as a security precaution.'
  fi
}
alias rm.='rmrf.'
.() {
  if [[ $# -eq 0 ]]; then
    cd .
  else
    source "$@"
  fi
}
alias ..='cd ..'
alias ...='cd ../..'
alias ....='cd ../../..'
alias .....='cd ../../../..'
v() {
  if [[ $# -eq 1 && -d $1 ]]; then
    (cd $1; $VIM_EDITOR .)
  else
    $VIM_EDITOR "$@"
  fi
}
alias v.='v .'
alias vi=v
alias vi.=v.
alias vim=v
alias vim.=v.
alias vimdiff="$VIM_EDITOR -d"
alias vd=vimdiff

alias el=elinks
remove-colors() {
  sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g"
}
alias md5sum=md5

alias chx='chmod +x'
ed() {
  command ed -p '*' "$@"
}
alias wh='which'
alias cmd='command'
prepend() {
  local text_to_prepend="$1"
  local file=$2
  local tmp_file="tmp_$file"

  echo "Prepend\n"
  echo "$text_to_prepend\n"
  read -q "answer?to $file? "
  echo "\n"
  if [[ $answer != "y" ]]; then return; fi

  echo 'Prepending...'
  echo $text_to_prepend > $tmp_file
  cat $file >> $tmp_file
  mv $tmp_file $file
  echo 'Done'
}

# Confs
al() {
  if [[ $# -eq 0 ]]; then
    $MAIN_EDITOR ~/.zshenv
  else
    alias $1
    if [[ $? -ne 0 ]]; then which $1; fi
  fi
}
alias conf="$MAIN_EDITOR ~/.zshrc"
alias sec="$MAIN_EDITOR ~/.secrets.zsh"
alias reload='. ~/.zshrc; . ~/.zshenv; . ~/.secrets.zsh'
alias rl='reload'
alias rel='reload'
alias i='arch -x86_64 zsh'

# Zsh
alias dirs='dirs -v'
alias '1'='cd -'
alias '2'='cd -2'
alias '3'='cd -3'
alias '4'='cd -4'
alias '5'='cd -5'
alias 6='cd -6'
alias 7='cd -7'
alias 8='cd -8'
alias 9='cd -9'
alias '--' -='cd -'

# Tmux
alias tl='tmux ls'
alias td='tmux detach'
alias kt='killall tmux'
t() {
  if [ $# -eq 0 ]; then
    tmux-start
  else
    tmux "$@"
  fi
}
tmux-start() {
  if (tmux ls | grep base | grep attached) >/dev/null 2>&1; then
    tmux-new-unnamed-session
  else
    tmux new -As base
  fi
}
tmux-new-unnamed-session() {
  local i=1
  while (tmux has-session -t ${i} 2>/dev/null); do; let i=i+1; done
  tmux new -s "$i"
}
tn() {
  if [ $# -eq 0 ]; then
    tmux new
  else
    tmux new -s "$1"
  fi
}
tk() {
  if [ $# -eq 0 ]; then
    tmux kill-session
  else
    for session in "$@"; do
      tmux kill-session -t "$session"
    done
  fi
}
ta() {
  if [ $# -eq 0 ]; then tmux attach; fi

  if [ -z "$TMUX" ]; then
    tmux attach -t "=$1"
  else
    tmux switch -t "=$1"
  fi
}
ts() {
  if [ $# -eq 0 ]; then
    tmux start-server \; source ~/.tmux.conf
    return
  fi

  tmux start-server \; source ~/.tmux/sessions/$1.conf
  ta "$1"
}
tgo() {
  tmux new-session -d -s go
  tmux send-keys -t go "cd $(pwd)" C-m
  tmux send-keys -t go 'ts rails' C-m
  tmux send-keys -t go 'ggo' C-m
  ta go
}
to() {
  if [ $# -ne 1 ]; then return; fi
  ta "$1" 2>/dev/null && return

  session_file=~/.tmux/sessions/$1.conf
  if [ -f "$session_file" ]; then
    ts "$1"
  else
    tmux new -d -s "$1"
    ta "$1"
  fi
}

# Git
alias gi='git init'
alias ginit='git init'
alias gl='git pull --rebase --prune'
alias glall='ls | xargs -P10 -I{} git -C {} pull --rebase --prune'
alias gs='git status'
alias gc='git commit'
alias ga='git add'
alias gaa='git add --all'
alias gaac='gaa && gc'
alias gbr='gb -r'
alias gca='gc --amend'
alias gca!='gca --no-edit'
alias gaaca='gaa && gca'
alias gaaca!='gaa && gca!'
alias gaacapf!='gaaca! && gpf'
alias gaacm='gaa && gcm'
gic() {
  if [ ! -d .git ]; then git init; fi
  gaacm "Initial commit"
}
alias gci='gic'
alias gco='git checkout'
alias gcob='gco -b'
alias gc-='gco -'
alias gco-='gco -'
alias gcom='gco master --'
alias gcl='git clone'
alias gclone='git clone'
gg() {
  last_command=$history[$((HISTCMD-1))]
  cd $(git_repo "$last_command")
}
git-repo() {
  echo "$1" | sed 's/.git$//' | sed 's/\/$//' | awk -F/ '{print $NF}'
}
ggcl() {
  git_repo=$(git-repo "$1")
  gcl "$@"
  cd "$git_repo" || return
}
alias gclg='ggcl'
gclv() {
  git_repo=$(git-repo "$1")
  gcl "$@"
  v "$git_repo"
}
ggclv() {
  ggcl "$@"
  v.
}
ex() {
  [ $# -eq 0 ] && return
  git_repo=$(git-repo "$1")
  cd ~/c/tmp
  if [ -d "$git_repo" ]; then
    cd "$git_repo" || return
    v.
  else
    ggclv "$@"
  fi
}
alias e='ex'
alias gm='git merge'
alias gm-='git merge -'
alias gmabort='git merge --abort'
gcm() {
  if [ $# -eq 0 ]; then
    git checkout $(git-main-branch)
  else
    gc -m "$*"
  fi
}
git-main-branch() {
  if [[ $(git branch --list 'main') ]]; then echo 'main'; else echo 'master'; fi
}
gcam() { gca -m "$*" }
alias gce='gc --allow-empty -m "Empty commit"'
gcem() { gc --allow-empty -m "$*" }
alias gclean='git clean -fd'
alias grhhc='grhh && gclean'
gd() {
  git diff "$@" | formatted-git-diff
}
formatted-git-diff() {
  sed -r "s/^([^-+ ]*)[-+ ]/\\1/" | eval $GIT_PAGER
}
alias gd!='git diff'
gsh() {
  git show "$@" | formatted-git-diff
}
alias gdc='gd --cached'
alias gdh='gd HEAD'
alias "gdh^"="gd 'HEAD^'"
alias glog='git log'
alias glo="git log --format=format:'%C(yellow)%h%C(reset) - %C(bold green)(%ar)%C(reset) %C(white)%s%C(reset) %C(dim white)- %an%C(reset)%C(auto)%d%C(reset)'"
alias glod="glo --date=format-local:'%a %b %d %Y %H:%M' --format=format:'%C(yellow)%h%C(reset) - %C(bold green)(%ad)%C(reset) %C(white)%s%C(reset) %C(dim white)- %an%C(reset)%C(auto)%d%C(reset)'"
alias gloa='glo --author=jerome'
alias gloda='glod --author=jerome'
alias gload='gloda'
alias lw='gload --since="last Monday midnight"'
glop() {
  glo -p "$@" | formatted-git-diff
}
alias gloo='git log --all --oneline --no-merges'
alias gloS='glo -S'
alias glo-='glo --'
alias gdt='git difftool'
alias gdtc='git difftool --cached'
alias gmt='git mergetool'
alias grm='git rm'
alias grmc='git rm --cached'
alias grv='git remote -v'
alias gre='grv'
alias gr='git reset'
alias grh='git reset HEAD'
alias "grh^"="git reset 'HEAD^'"
alias grhh='git reset HEAD --hard'
alias "grhh^"="git reset --hard 'HEAD^'"
alias gst='git stash -u'
alias gstm='gst -m'
alias gstp='git stash pop'
alias gstl='git stash list'
alias gstc='git stash clear'
alias gsts='git stash save'
alias grb='git rebase'
alias grb-='git rebase -'
grbm() { git rebase $(git-main-branch) }
alias grbi='git rebase -i'
alias grbi2='git rebase -i HEAD~2'
alias grbi3='git rebase -i HEAD~3'
alias grbi4='git rebase -i HEAD~4'
alias grbi5='git rebase -i HEAD~5'
grbim() { git rebase -i $(git-main-branch) }
alias grbir='git rebase -i --root'
alias gcon='git rebase --continue'
alias grcon='gcon'
alias gaacon='gaa && gcon'
alias grabort='git rebase --abort'
alias gsk='git rebase --skip'
alias gb='git branch --sort=-committerdate'
gbcp() { echo $(current-git-branch) | pbcopy }
alias gbs='git branch -D sav &>/dev/null; git branch sav'
alias gcs='git checkout sav'
alias gbd='git branch -d'
alias gbD='git branch -D'
alias gbDs="git branch | remove-colors | cut -c3- | egrep -i '^s+a+v+.*' | xargs git branch -D"
alias gbDa='git branch | remove-colors | egrep -v "master|main|\*" | xargs git branch -D'
alias gbD-="gbD @{-1}"
gbDi() {
  git branch --sort=-committerdate | remove-colors | egrep -v "master|main|\*" | cut -c3- > /tmp/branches && \
    cp /tmp/branches /tmp/branches-to-keep && \
    $MAIN_EDITOR /tmp/branches-to-keep && \
    comm -23 <(sort /tmp/branches) <(sort /tmp/branches-to-keep) | xargs 2> /dev/null git branch -D
}
alias gbm='gb -m'
# alias gbDs="git-list-branches | egrep -i '^s+a+v+.*' | xargs git branch -D"
# alias gbDa='git-list-branches | grep -v "master\|$(current-git-branch)" | xargs git branch -D'
# git-list-branches() {
#   git for-each-ref --format="%(refname:short)" HEAD refs/heads
# }
alias gbi='git bisect'
alias gignore='git update-index --assume-unchanged'
alias gunignore='git update-index --no-assume-unchanged'
alias gignored='git ignored'
alias gp='git push'
alias gpf='gp --force-with-lease'
alias gpf!='gp --force'
gpu() {
  if [[ $# -eq 0 ]]; then
    local remote=$(github-fork-exists && echo 'jeromedalbert' || echo 'origin')
    gp -u $remote $(current-git-branch)
  else
    gp -u "$@"
  fi
}
github-fork-exists() {
  git remote get-url jeromedalbert &>/dev/null
}
gpuf() {
  if [[ $# -eq 0 ]]; then
    gp -u -f origin $(current-git-branch)
  else
    gp -u -f "$@"
  fi
}
gpd() {
  if [[ $# -eq 0 ]]; then
    gp -d origin $(current-git-branch)
  else
    gp -d "$@"
  fi
}
alias gclo-'git clone'
alias gx='gitx'
alias ggx='gitx'
alias gu='gitup'
alias git-branch-previous='git check-ref-format --branch "@{-1}"'
ggo() {
  current-git-branch > .git/previous_branch
  gaacm "current work"
  gcm
}
gback() {
  if [[ -e '.git/previous_branch' ]]; then
    gco $(cat .git/previous_branch)
    rm .git/previous_branch
  fi
  last_commit_message=$(git log -1 --pretty=%B)
  if [[ $last_commit_message == 'current work' ]]; then grh^; fi
  unset last_commit_message
}
alias gcurr='gaacm "current work"'
alias gcur=gcurr
grebase() {
  local branch=${1:-$(git-main-branch)}
  git checkout $branch && gl && gc- && grb-
}
gmerge() {
  local branch=${1:-$(git-main-branch)}
  git checkout $branch && gl && gc- && gm-
}
alias gt='git tag --sort=-v:refname'
alias gcp='git cherry-pick'
alias gcp-='git cherry-pick -'
alias gcpc='git cherry-pick --continue'
alias gcpa='git cherry-pick --abort'
fix() {
  vim +"silent! /<<<<<<<" $(git diff --name-only --diff-filter=U | xargs)
}
alias fx='fix'
alias gstats='git shortlog -sn'
alias gsa='git submodule add'
git-submodule-remove() {
  local submodule="$@"
  git submodule deinit -f $submodule
  rm -rf .git/modules/$submodule
  git rm -f $submodule
}
alias gsr='git-submodule-remove'
alias grev='git revert'
alias grevh='git revert HEAD'
alias grevnoe='git revert --no-edit'
git-churn() {
  git log --all -M -C --name-only --format='format:' "$@" \
    | sort \
    | grep -v '^$' \
    | uniq -c \
    | sort -n \
    | awk 'BEGIN {print "count\tfile"} {print $1 "\t" $2}'
}
git-unchanged-since() {
  git log --name-only --since="$@" --pretty='format:' '*.rb' | egrep '^(app|lib)/' > /tmp/changed
  git ls-files '*.rb' | egrep '^(app|lib)/' > /tmp/all
  comm -23 <(sort -u /tmp/all) <(sort -u /tmp/changed)
}
alias squash='git reset --soft $(git-main-branch); gaacm "Squashed commits"'
alias squashi='git reset $(git commit-tree HEAD^{tree} -m "Initial commit")'

# Directories
alias st2='cd ~/Library/Application\ Support/Sublime\ Text\ 2/Packages'
alias st3='cd ~/Library/Application\ Support/Sublime\ Text\ 3/Packages'
alias .vim='cd ~/.vim'
alias c='cd ~/c'
alias desk='cd ~/Desktop'
alias de='desk'

# SSH
alias sshconf="$MAIN_EDITOR ~/.ssh/config"
alias sshc='sshconf'
alias sshk="$MAIN_EDITOR ~/.ssh/known_hosts"
alias ssh-key='cat ~/.ssh/id_jerome.pub | tee >(pbcopy)'
alias ssh-keys='ssh-key'

# Entertainment
alias cowfortune='clear && fortune -a | cowsay | lolcat'
alias cowfact="clear && elinks -dump http://randomfunfacts.com  | sed -n '/^| /p' | tr -d \| | cowsay | lolcat"
alias dunnet='emacs -batch -l dunnet'
alias emacs-games='ls /usr/share/emacs/22.1/lisp/play/*.elc | column -t'
snow() {
  clear;while :;do echo $LINES $COLUMNS $(($RANDOM%$COLUMNS));sleep 0.1;done|awk '{a[$3]=0;for(x in a) {o=a[x];a[x]=a[x]+1;printf "\033[%s;%sH ",o,x;printf "\033[%s;%sH*\033[0;0H",a[x],x;}}'
}

# Fzf
j() {
  if [ "$#" -gt 0 ]; then
    # _z "$@"
    # cd "$(_z -l 2>&1 | fzf -f "$*" | sort -nr | head -n 1 | sed 's/^[0-9,.]* *//')"
    cd "$(_z -l 2>&1 | fzf -f "$*" | head -n 1 | sed 's/^[0-9,.]* *//')"
  else
    cd "$(_z -l 2>&1 | fzf --height 40% --reverse --tac --query "$*" | sed 's/^[0-9,.]* *//')"
  fi
}

flog() {
  local commits=$(
    glo --color=always "$@" |
      fzf --ansi --no-sort --height 100% \
      --preview "echo {} | grep -o '[a-f0-9]\{7\}' | head -1 |
      xargs -I@ sh -c 'git show --color=always @'"
  )
  if [[ -n "$commits" ]]; then
    local hashes=$(printf "$commits" | cut -d' ' -f2 | tr '\n' ' ')
    git show $hashes
  fi
}
freflog() {
  local hash=$(
    git reflog --color=always "$@" |
      fzf --no-multi --ansi --no-sort --height 100% \
      --preview "git show --color=always {1}"
  )
  echo $hash
}

# Ruby / Rails
bundle() {
  command bundle "$@"
  if [[ $? -eq 0 && $1 == 'gem' ]]; then cd $2; fi
}
alias b='bundle'
alias be='bundle exec'
alias bo='bundle open'
alias bi='bundle install'
alias bu='bundle update'
bundle-path() {
  VISUAL=echo bundle open $1
}
alias bp='bundle-path'
bs() { ag -C "$@" $(bundle show --paths) }
rails() {
  binstub-command rails "$@"
  if [[ $? -eq 0 && $1 == 'new' ]]; then cd $2; fi
}
alias rake='binstub-command rake'
alias rspec='binstub-command rspec'
alias spring='binstub-command spring'
alias brakeman='binstub-command brakeman'
alias kamal='bin/kamal'
alias importmap='bin/importmap'
binstub-command() {
  local cmd=$1
  shift
  if [[ -e bin/$cmd ]]; then bin/$cmd "$@"; else command $cmd "$@"; fi
}
alias im='importmap'
alias bd='bin/dev'
alias r='rails'
alias rs='rails server'
alias rg='rails generate'
alias rgm='rails generate migration'
alias rgs='rails generate scaffold'
alias rdm='rails destroy migration'
alias rd='rails destroy'
ruby-console() {
  if [[ -e 'config/application.rb' ]]; then bin/rails c
  elif [[ -e 'bin/console' ]]; then bin/console
  else irb
  fi
}
alias rc='ruby-console'
alias rcs='rails c --sandbox'
alias rr='rails routes'
alias rrs='rails restart'
alias rss='rrs'
alias rst='rrs'
alias rdb='rails db'
alias mi='rake db:migrate'
alias ro='rake db:rollback'
alias romi='ro && mi'
alias rT='rake -T'
alias st='spring stop'
alias strc='st && rc'
alias ss='spring status'
alias rhash='asdf reshim ruby'
gman() { man $(gem-path $1)/man/* }
gmcd() { cd $(gem-path $1) }
gem-path() {
  VISUAL=echo gem open $1
}
alias gmp='gem-path'
gmb() {
  open $(gem info $1 | awk '/Homepage/ { print $2 }')
}

alias ocov='open coverage/index.html '
alias cov='COVERAGE=true rspec && ocov'
steps() {
  git checkout $(git-main-branch) &>/dev/null
  local main_mig_num=$(ls db/migrate | wc -l)
  git checkout - &>/dev/null
  local mig_num=$(ls db/migrate | wc -l)
  local delta=$(($mig_num - $main_mig_num))
  echo $delta
}
alias sw='stree write'
rdbg() {
  if [[ $# -eq 0 ]]; then
    rdbg -An
  else
    command rdbg "$@"
  fi
}
alias dbundle='ruby ~/c/rubygems/bundler/spec/support/bundle.rb'
alias dgem='ruby -I ~/c/rubygems/lib ~/c/rubygems/exe/gem'

# Python
alias py='python'

# Apps / Binaries
alias subl="/Applications/Sublime\ Text\ 2.app/Contents/SharedSupport/bin/subl"
alias subl.='subl .'
alias subl3='command subl'
alias subl3.='subl3 .'
cursor() {
  (/Applications/Cursor.app/Contents/MacOS/Cursor "$@" >/dev/null 2>&1 &)
}
alias code='cursor'
alias cur='cursor'
alias c.='cur .'
alias say_good='say -v Good ooooooooooooooooooooooooooooooooooooooooooooooooooo'
alias say_bad='say -v Bad ooooooooooooooooooooooooooooooooooooooooooooooooooo'
alias keyboard_disable='sudo kextunload /System/Library/Extensions/AppleUSBTopCase.kext/Contents/PlugIns/AppleUSBTCKeyboard.kext'
alias keyboard_enable='sudo kextload /System/Library/Extensions/AppleUSBTopCase.kext/Contents/PlugIns/AppleUSBTCKeyboard.kext'
alias iphone="open '/Applications/Xcode.app/Contents/Developer/Applications/Simulator.app'"
localip() {
  local ip=$(ipconfig getifaddr en0)
  echo $ip | tr -d '\n' | pbcopy
  echo $ip
}
alias privateip='localip'
publicip() {
  local ip=$(curl -s ipinfo.io/ip)
  echo $ip | pbcopy
  echo $ip
}
alias ip='publicip'
alias myip='publicip'
iploc() {
  curl -s ipinfo.io/"$@" | jq '.city + ", " + .region + ", " + .country' | tr -d '"'
}
alias whereami='iploc'
alias o='open'
alias o.='open .'
alias toggle-cam='tcam'
alias dpad='sudo kextunload /System/Library/Extensions/AppleUSBMultitouch.kext' # 2> /dev/null"
alias epad='sudo kextload /System/Library/Extensions/AppleUSBMultitouch.kext'
alias emouse='dpad'
alias dmouse='epad'
alias archey='archey -c'
alias mounted='mount | column -t'
sman() { man "${1}" | col -b | subl }
alias rtop='top -o rsize'
alias ctop='top -o cpu'
alias sub='subliminal download -l en'
alias sub2='filebot -get-subtitles'

minivim() {
  conf=$(awk 'NF > 0 { printf ":" $0 "\\\\n" }' ~/.vimrc.minimal)
  echo "${conf}" | tee >(pbcopy)
}

killui() {
  for app in "Dock" "Finder" "SystemUIServer"; do
    killall "${app}"
  done
}

rails_new() {
  ~/c/boilerplate/rails-template/rails-new "$@"
  if [[ $? -eq 0 && -d "$1" ]]; then cd $1; fi
}
alias rn='rails-new'

gem_new() {
  local gem_new_path=~/c/boilerplate/gem-new
  bundle exec --gemfile $gem_new_path/Gemfile $gem_new_path/exe/gem-new "$@"
  if [[ $? -eq 0 && -d "$1" ]]; then cd $1; fi
}
#alias gn='gem_new'

mkpwd() {
  local max_chars=${1:-28}
  cat /dev/urandom | LC_ALL=C tr -dc 'a-zA-Z0-9' | fold -w $max_chars | head -n 1 | tee >(pbcopy)
}
mkpwd2() {
  local password=$(openssl rand -base64 300 | tr -d '\n=/+')
  local max_chars=${1:-28}
  echo $password | cut -c-$max_chars | tee >(pbcopy)
}
alias password='mkpwd'
alias mkpw='mkpwd'
alias pw='mkpw'

alias fd='fd --type f'

alias ng='ngcp && ngrok http --domain $NGROK_DOMAIN 5000'
alias ngcp='echo "https://$NGROK_DOMAIN" | pbcopy'
smee() {
  echo ${SMEE_URL} | pbcopy
  command smee -u ${SMEE_URL} -p 5000 "$@"
}
alias smeecp='echo ${SMEE_URL} | pbcopy'
alias smeego='open ${SMEE_URL}'

tess() {
  local file=$1
  if [[ -z $file ]]; then
    file=$(ls -dt ~/Desktop/* | head -n 1)
  fi
  tesseract $file stdout | tee >(pbcopy)
}

gq() {
  local escaped_query=$(printf "%q" ${@: -1})
  curl -X POST -H 'Content-Type: application/json' $1 -d "{ \"query\": \"$escaped_query\" }"
}
alias pj='pbpaste | jq .'
parsecron() {
  ruby -e "require 'cronex'; puts Cronex::ExpressionDescriptor.new('$1').description" \
    | tee >(pbcopy)
}
alias curljs='curl -H "Content-type: application/json"'
curlgql() {
  curljs --X POST -s -w '%{time_total}' "$@" | jq
}
alias unused='unused -t .tags'

alias chrome_no_ssl='/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --ignore-certificate-errors --ignore-urlfetcher-cert-requests &>/dev/null'

bench() {
  if [[ $# -eq 0 ]]; then browsertime --help; return; fi
  browsertime --headless --skipHar --resultDir=/tmp "$@"
  echo
  cat /tmp/browsertime.json | jq -r '.[0].statistics.timings.pageTimings | "Average DOM Load Time: \(.domContentLoadedTime.mean) ms\nAverage Load Time: \(.pageLoadTime.mean) ms\n\nMean DOM Load Time: \(.domContentLoadedTime.mean) ms\nMean Load Time: \(.pageLoadTime.mean) ms"'
}

################################################################################

# eval "$(zoxide init bash)"
source ~/.vim/z.sh
unalias z 2> /dev/null
z() {
   [ $# -gt 0 ] && _z "$*" && return
   cd "$(_z -l 2>&1 | fzf --height 40% --nth 2.. --reverse --inline-info +s --tac --query "${*##-* }" | sed 's/^[0-9,.]* *//')"
}

# if [ -f "$(brew --prefix)/opt/bash-git-prompt/share/gitprompt.sh" ]; then
#   __GIT_PROMPT_DIR=$(brew --prefix)/opt/bash-git-prompt/share
#   GIT_PROMPT_ONLY_IN_REPO=1
#   source "$(brew --prefix)/opt/bash-git-prompt/share/gitprompt.sh"
# fi
#

################################################################################

# +--------+
# | Neovim |
# +--------+

alias vim='nvim'
alias vi='nvim'
alias svim='sudoedit'
alias dvim="vim -u /usr/share/nvim/archlinux.vim" # nvim with default config
alias nvimc='rm -I $VIMCONFIG/swap/*'             # clean nvim swap file
alias nvimcu='rm -I $VIMCONFIG/undo/*'            # clean the vim undo
alias nviml='nvim -w $VIMCONFIG/vimlog "$@"'      # log the keystrokes

# fast vim for big files / big oneliner
alias lvim='\vim -c "set nowrap|syntax off"'


alias v='vim'
alias vim='vim'
alias g='git'
alias t='type'
alias ls='eza --icons --color-scale all'
alias ll='ls -lah'

# bash
alias search-command='compgen -c | sort -u | fzf'
alias cpwd='pwd | tr -d "\n" | c'

# Remove all previous environment defined aliases.
#
unalias -a

# Aliases.
#
# -- Coreutils aliases --
alias mc='_f() { mkdir -p "$@" && command cd "$@"; }; _f'
alias mv='/bin/mv -iv'
alias rm='/bin/rm -i'
alias rmrf='/bin/rm -rf'
# -- Permissions aliases --
alias 664='chmod 664'
alias 775='chmod 775'
# -- Navigation aliases --
alias -- -='cd -'
alias -- ~='cd ~'
alias ..='cd ..'
alias ...='cd ../..'
alias ....='cd ../../..'
# -- Docker aliases --
alias d='docker'
alias dc='docker-compose'
# -- Git aliases --
alias g~='cd "$(git rev-parse --show-toplevel)"'
alias ga='fzf_git_add'
alias gll='fzf_git_log clean'
alias glla='fzf_git_log all'
alias glS='fzf_git_log_pickaxe'
alias grl='fzf_git_reflog'
alias gu='fzf_git_unadd'
# -- History aliases --
alias hi=history
alias hg='history | rg'
alias hm='history -n'
# -- List aliases --
alias dir='ls -l --group-directories-first'
alias td='tree -C -d'
alias tdl='tree -C -d -L'
alias tl='eza --tree --group-directories-first -L'

# -- Miscellaneous aliases --
alias be='bundle exec'
alias cwd='copy_working_directory'
alias df.='df -h .'
alias fkill='fzf_kill'
alias lynx='lynx --accept_all_cookies'
alias math='set -f; _f() { echo $@ | bc; set +f; }; _f'
alias mdi='meld'
alias p='bat'
alias pn='pnpm'
alias px='pnpx'
alias pping='prettyping --nolegend -i 5'
alias psu='ps -u $USER -f'
alias qmv='qmv -d -f do'
alias rsync='rsync --archive --human-readable --info=progress2 --verbose'
alias scp='/usr/bin/scp -r'
alias src='. ~/.bashrc'
alias ssh='/usr/bin/ssh'
alias ssh-add='/usr/bin/ssh-add'
alias sudo='sudo '
alias wl='wc -l'
alias x=exit
alias ytest='CI=true yarn test --colors'


# General environment variables.
#
export EDITOR=nvim

export LESSHISTFILE=-
# LS_COLORS (refer to: https://is.gd/6MzI27)
#   mi - completion options color
#   so - completion matching-prefix color
export LS_COLORS="no=00:fi=00:di=38;5;111:ln=38;5;117:pi=38;5;43:bd=38;5;212:\
cd=38;5;219:or=30;48;5;203:ow=38;5;75:so=38;5;252;48;5;0:su=38;5;168:\
ex=38;5;156:mi=38;5;115:\
*.avi=38;2;175;215;175:*.mpg=38;2;175;215;175:*.mp4=38;2;244;180;180:\
*.astro=38;2;110;222;222:*.md=38;2;213;218;180:*README=38;2;213;218;180:\
*.pdf=38;2;218;218;218"
# EZA_COLORS (refer to: man eza_colors)
export EZA_COLORS="da=38;5;252:sb=38;5;204:sn=38;5;43:xa=8:\
uu=38;5;245:un=38;5;241:ur=38;5;223:uw=38;5;223:ux=38;5;223:ue=38;5;223:\
gr=38;5;153:gw=38;5;153:gx=38;5;153:tr=38;5;175:tw=38;5;175:tx=38;5;175:\
gm=38;5;203:ga=38;5;203:mp=3;38;5;111:im=38;2;180;150;250:vi=38;2;255;190;148:\
mu=38;2;255;175;215:lo=38;2;255;215;183:cr=38;2;240;160;240:\
do=38;2;200;200;246:co=38;2;255;119;153:tm=38;2;148;148;148:\
cm=38;2;230;150;210:bu=38;2;95;215;175:sc=38;2;110;222;222"
export PAGER=less
export MANPAGER='nvim +Man!'

# What platform are we running on.
export OS=$(uname)

# Customizations per platform.
if [[ $OS == "Linux" ]]; then
    export SHELL='/bin/bash'
    alias ip='ip --color=auto'
    alias dr14_tmeter='/usr/local/dr14_t.meter/dr14_tmeter'
    alias free='free -th'
    alias mplayer='mplayer 2>/dev/null'
    alias updatedb='sudo /usr/bin/updatedb'
elif [[ $OS == "Darwin" ]]; then
    export SHELL='/opt/homebrew/bin/bash'
    export PGGSSENCMODE='disable' # Reference: https://is.gd/flzYH7
    alias locate='mdfind -name'
fi

# Functions.
#
brew_config() {
  if [[ $OS == "Linux" ]]; then
    if ! [[ -x $(command -v /home/linuxbrew/.linuxbrew/bin/brew 2>/dev/null) ]]; then
        echo 'Note: brew is not available.'
        return
    fi
    export HOMEBREW_PREFIX="/home/linuxbrew/.linuxbrew";
    export HOMEBREW_CELLAR="/home/linuxbrew/.linuxbrew/Cellar";
    export HOMEBREW_REPOSITORY="/home/linuxbrew/.linuxbrew/Homebrew"
    PATH=$HOMEBREW_PREFIX/bin:$PATH
    MANPATH=$HOMEBREW_PREFIX/share/man:$MANPATH
    export HOMEBREW_AUTO_UPDATE_SECS=7200
elif [[ $OS == "Darwin" ]]; then
    if ! [[ -x $(command -v /opt/homebrew/bin/brew 2>/dev/null) ]]; then
        echo 'Note: brew is not available.'
        return
    fi
    export HOMEBREW_PREFIX="/opt/homebrew";
    export HOMEBREW_CELLAR="/opt/homebrew/Cellar";
    export HOMEBREW_REPOSITORY="/opt/homebrew"
    PATH=$HOMEBREW_PREFIX/opt/coreutils/libexec/gnubin:$HOMEBREW_PREFIX/opt/gnu-tar/libexec/gnubin:$HOMEBREW_PREFIX/opt/gnu-sed/libexec/gnubin:$HOMEBREW_PREFIX/bin:$PATH
    MANPATH=$HOMEBREW_PREFIX/opt/coreutils/libexec/gnuman:$HOMEBREW_PREFIX/share/man:$MANPATH
    export HOMEBREW_AUTO_UPDATE_SECS=7200
  else
    echo 'Error: unsupported platform'
    return
  fi
}

copy_working_directory() {
    if [[ $OS == "Linux" ]]; then
        echo -n ${PWD/#$HOME/\~} | tr -d "\r\n" | xclip -selection clipboard -i
    elif [[ $OS == "Darwin" ]]; then
        echo -n ${PWD/#$HOME/\~} | tr -d "\r\n" | pbcopy
    fi
    # Also copy current directory to a tmux paste buffer if tmux is active.
    if [[ -n $TMUX ]]; then
        echo -n ${PWD/#$HOME/\~} | tr -d "\r\n" | tmux load-buffer -
    fi
}

custom_config() {
    # Manually load Bash Completion for Linux if necessary.
    [[ $OS == "Linux" && -z "$BASH_COMPLETION_VERSINFO" ]] && . /etc/profile.d/bash_completion.sh

    # If Homebrew is not setup, just return.
    if [[ -z $HOMEBREW_PREFIX ]]; then
        return
    fi

    # Manually load Bash Completion for macOS from Homebrew.
    [[ $OS == "Darwin" ]] && . $HOMEBREW_PREFIX/etc/profile.d/bash_completion.sh

    # Note, custom Bash completions are stored in ~/dotfiles/completions.
    # These are then symlinked to ~/.local/share/bash-completion for automatic
    # lazy-loading. Refer to: https://is.gd/CV7ufa

    # 'fzf' utility.
    . $HOMEBREW_PREFIX/opt/fzf/shell/key-bindings.bash
    export FZF_DEFAULT_OPTS='
      --height 75% --multi --reverse --margin=0,1
      --bind ctrl-f:page-down,ctrl-b:page-up
      --bind pgdn:preview-page-down,pgup:preview-page-up
      --marker="✚" --pointer="▶" --prompt="❯ "
      --no-separator --scrollbar="█" --border
      --color bg:#080808,bg+:#262626,border:#303030,fg:#b2b2b2,fg+:#dadada
      --color gutter:#262626,header:#80a0ff,hl:#f09479,hl+:#f09479
      --color info:#cfcfb0,marker:#f09479,pointer:#ff5189,prompt:#87afff
      --color spinner:#36c692
    '
    export FZF_DEFAULT_COMMAND='fd --type f --color=never'
    export FZF_CTRL_T_COMMAND="$FZF_DEFAULT_COMMAND"
    export FZF_CTRL_T_OPTS='--preview "bat --color=always --line-range :500 {}"'
    export FZF_ALT_C_COMMAND='fd --type d . --color=never'
    export FZF_ALT_C_OPTS='--preview "tree -C {} | head -100"'

    # 'zoxide' utility.
    eval "$(zoxide init bash)"
    export _ZO_EXCLUDE_DIRS=$HOME:$HOME/Music/*
    export _ZO_MAXAGE='20000'
    export _ZO_FZF_OPTS="
      $FZF_DEFAULT_OPTS --no-multi --no-sort  --exit-0 --select-1
      --preview 'eza --no-quotes --color=always --color-scale-mode=fixed --group-directories-first --oneline {2..}'
    "

    # 'bat' configuration.
    export BAT_CONFIG_PATH="$HOME/dotfiles/bat.conf"
}

dev_config() {
    if [[ -z $HOMEBREW_PREFIX ]]; then
        return
    fi

    if [[ -f $HOMEBREW_PREFIX/share/chruby/chruby.sh ]]; then
        # chruby is slow, instead simply set environment variables explicitly.
        #   . $HOMEBREW_PREFIX/share/chruby/chruby.sh
        #   chruby 3.2.5
        export RUBY_VERSION=3.2.5
        export RUBY_ROOT=$HOME/.rubies/ruby-$RUBY_VERSION
        export GEM_ROOT=$RUBY_ROOT/lib/ruby/gems/3.2.0
        export GEM_HOME=$HOME/.gem/ruby/$RUBY_VERSION
        export GEM_PATH=$GEM_HOME:$GEM_ROOT
        PATH=$GEM_HOME/bin:$RUBY_ROOT/bin:$PATH
        hash -r
    fi
    if [[ -x $HOMEBREW_PREFIX/bin/fnm ]]; then
        eval "$(fnm env)"
        export PNPM_HOME=$HOME/.local/share/pnpm
        PATH=$PATH:$PNPM_HOME
    fi
    if [[ -x ~/.cargo/bin ]]; then
        PATH=$PATH:~/.cargo/bin
    fi
    if [[ -d ~/projects/go ]]; then
        export GOPATH=~/projects/go
        PATH=$PATH:$GOPATH/bin
    fi
}

find_by_size() {
    if [[ $# -eq 0 ]]; then
        echo "Usage: llfs <size> (e.g. 100k, +1M, +1G)"
    else
        find . -type f -size "$1" -exec eza --long {} \; ;
    fi
}


fzf_git_add() {
    local selections=$(
      git ls-files -m -o --exclude-standard | \
        fzf --ansi \
            --preview 'if (git ls-files --error-unmatch {1} &>/dev/null); then
                           git diff --color=always {1} | delta
                       else
                           bat --color=always --line-range :500 {1}
                       fi'
    )
    if [[ -n $selections ]]; then
        git add --verbose $selections
    fi
}

fzf_git_log() {
    local command='ll'
    if [[ "$1" == "all" ]]; then
        command='lla'
    fi
    shift # Consume the first argument of this function
    local selection=$(
      git $command --color=always "$@" | \
        fzf --no-multi --ansi --no-sort --no-height \
            --preview "echo {} | grep -o '[a-f0-9]\{7\}' | head -1 |
                       xargs -I@ sh -c 'git show --color=always @' |
                       delta"
    )
    if [[ -n $selection ]]; then
        local commit=$(echo "$selection" | sed 's/^[* |]*//' | awk '{print $1}' | tr -d '\n')
        git show $commit
    fi
}

fzf_git_log_pickaxe() {
    if [[ $# -eq 0 ]]; then
        echo 'Usage: glS <search-term>'
        return
    fi
    local selection=$(
      git log --oneline --color=always -S "$@" |
        fzf --no-multi --ansi --no-sort --no-height \
            --preview 'git show --color=always {1} | delta'
    )
    if [[ -n "$selection" ]]; then
        local commit=$(echo "$selection" | awk '{print $1}' | tr -d '\n')
        git show $commit
    fi
}

fzf_git_reflog() {
    local selection=$(
      git reflog --color=always "$@" |
        fzf --no-multi --ansi --no-sort --no-height \
            --preview 'git show --color=always {1} | delta'
    )
    if [[ -n "$selection" ]]; then
        git show $(echo "$selection" | awk '{print $1}')
    fi
}

fzf_git_unadd() {
    local changes=$(git diff --name-only --cached | fzf --ansi | tr '\n' ' ')
    if [[ -n "$changes" ]]; then
        git reset HEAD $changes
    fi
}

h() {
    local navi_command='navi --print --fzf-overrides "--no-multi --no-height --no-sort"'
    if [[ $# -eq 0 ]]; then
        eval $navi_command
    else
        eval $navi_command --query "$@"
    fi
}


mux_command() {
    if [[ $# -eq 1 ]] && [[ $1 == "stop" ]]; then
        # Automatically stop the current session.
        tmuxinator stop $(tmux display-message -p '#S')
    else
        tmuxinator "$@"
    fi
}

packages() {
    # bash-seafly-prompt (https://github.com/bluz71/bash-seafly-prompt)
    #
    # Install the package if it does not exist.
    if ! [[ -d ~/.bash-packages/bash-seafly-prompt ]]; then
        git clone --depth 1 https://github.com/bluz71/bash-seafly-prompt ~/.bash-packages/bash-seafly-prompt
    fi
    SEAFLY_SUCCESS_COLOR=$(echo -ne '\e[38;5;4m')
    seafly_pre_command_hook="seafly_pre_command"
    seafly_prompt_prefix_hook="seafly_prompt_prefix"
    # Custom colors for prompt prefix; for performance reasons calculate the
    # colors outside the 'seafly_prompt_prefix' function.
    . ~/.bash-packages/bash-seafly-prompt/command_prompt.bash
}

seafly_pre_command() {
    if [[ -n $HOMEBREW_PREFIX ]]; then
        history -a
        __zoxide_hook
    else
        history -a
    fi
}

seafly_prompt_prefix() {
    if [[ -f Gemfile ]]; then
        echo "\e[38;5;1m◢"
    elif [[ -f package.json ]]; then
        echo "\e[38;5;79m⬢"
    elif [[ -f Cargo.toml ]]; then
        echo "\e[38;5;208m●"
    elif [[ -f pubspec.yaml ]]; then
        echo "\e[38;5;12m◀"
    fi
}

# # Set environment.
# #
# user_paths
# brew_config
# custom_config
# packages
# dev_config
# shell_config

################################################################################

# Management
alias dots="cd ~/.dotfiles && vim"
alias reload='source ~/.bash_profile && echo "sourced ~/.bash_profile"'
alias redot='cd ~/.dotfiles && gpp && rake install; cd -'

alias hosts='sudo vim /etc/hosts'
alias vrb='vim -c "setf ruby"'

# http://www.hogbaysoftware.com/products/plaintext
alias text='cd ~/Dropbox/PlainText && vim'

# Shell
alias la='ls -alh'
alias cdd='cd -'  # Back to last directory
alias cdr='cd $(git rev-parse --show-toplevel)'
# Back to git root - from https://twitter.com/thorstenball/status/1223218245592911878
alias pg='ps aux | head -n1; ps aux | grep -i'
alias tf='tail -F -n200'
alias ..='cd ..'
alias ...='cd ../..'
alias ....='cd ../../..'
alias ip="ifconfig|grep broadcast"  # List IPs

# Portable ls with colors
if ls --color -d . >/dev/null 2>&1; then
  alias ls='ls --color=auto'  # Linux
elif ls -G -d . >/dev/null 2>&1; then
  alias ls='ls -G'  # BSD/OS X
fi

# Ruby on Rails
alias sx="[ -f script/console ] && script/console --sandbox || bundle exec rails console --sandbox"
alias sdb="[ -f script/dbconsole ] && script/console --include-password || bundle exec rails dbconsole --include-password"
alias f="script/foreman_turbux"

# Phoenix or Ruby on Rails
alias mig="if [ -f mix.exs ]; then mix ecto.migrate; elif [ -f Rakefile ]; then bundle exec rake db:migrate; else echo 'Did not detect Phoenix or Rails.'; fi"
alias ss="if [ -f mix.exs ]; then mix phx.server; elif [ -f Rakefile ]; then rails server; else echo 'Did not detect Phoenix or Rails.'; fi"
alias sc="if [ -f mix.exs ]; then iex -S mix; elif [ -f Rakefile ]; then bundle exec rails console; else echo 'Did not detect Phoenix or Rails.'; fi"

# Ruby
alias be="bundle exec"

# Elixir
alias smix="iex -S mix"

# Docker Compose (as seen e.g. in https://thoughtbot.com/blog/rails-on-docker)
alias dew="docker-compose exec web"

# Git

# Determine if the main Git branch is "master" or "main". (Assumes it's one of those two.)
# https://stackoverflow.com/a/66622363/6962
function git_main_branch {
  [ -f "$(git rev-parse --show-toplevel)/.git/refs/heads/master" ] && echo "master" || echo "main"
}

alias gl="git pull"
alias gpp="git pull && git push"
alias gppp="git push -u"  # Can't pull because you forgot to track? Run this.
alias go="git checkout"
alias gb="git checkout -b"
alias got="git checkout -"
alias gom='git checkout `git_main_branch`'
alias grb='git rebase -i @{push}'
alias gr="git branch -d"
alias grr="git branch -D"
alias gcp="git cherry-pick"
alias gcpp="git cherry-pick -"  # "cherry-pick previous", e.g. the head of the branch we just left
alias gam="git commit --amend --allow-empty"
alias gamm="git add --all && git commit --amend --allow-empty --no-edit"
alias gammf="gamm --no-verify"
alias gba="git rebase --abort"
alias gbc="git add -A && git rebase --continue"
alias gbm='git fetch origin `git_main_branch` && git rebase origin/`git_main_branch`'
alias gap="git add --intent-to-add . && git add -p"  # Like "git add -p" but also ask about any newly added files.

# Work

# Sometimes the camera in my Cinema Display stops working. This fixes it.
alias fixcam="sudo killall VDCAssistant"

# Sometimes the time in my VM is off. This fixes it.
alias fixtime="sudo service ntp stop; sudo ntpd -gq; sudo service ntp start"

################################################################################

docker-aliases


#!/usr/bin/env bash

# docker
alias dc='docker-compose'
alias dps='docker-compose ps'
alias dstart='docker-compose start'
alias dstop='docker-compose stop'
alias dup='docker-compose up'
alias dub='docker-compose up --build'
alias ddown='docker-compose down'
alias drestart='docker-compose restart'
# usage: dexec COMMAND
alias dexec='docker exec -it /bin/sh'
# update images
alias dpull='docker pull'



# +--------+
# | docker |
# +--------+
alias dockls="docker container ls | awk 'NR > 1 {print \$NF}'"                  # display names of running containers
alias dockRr='docker rm $(docker ps -a -q)'                                     # delete every containers / images
alias dockRr='docker rm $(docker ps -a -q) && docker rmi $(docker images -q)'   # delete every containers / images
alias dockstats='docker stats $(docker ps -q)'                                  # stats on images
alias dockimg='docker images'                                                   # list images installed
alias dockprune='docker system prune -a'                                        # prune everything
alias dockceu='docker-compose run --rm -u $(id -u):$(id -g)'                    # run as the host user
alias dockce='docker-compose run --rm'

# +----------------+
# | docker-compose |
# +----------------+

alias docker-compose-dev='docker-compose -f docker-compose-dev.yml' # run a different config file than the default one



#!/bin/bash
# shellcheck disable=SC1004

++ export CROSS_CONTAINER_ENGINE=podman

dockerrun() { eval docker run --rm --interactive --tty "$*"; }
dockerrunu() { eval dockerrun --user="$(id -u):$(id -g)" "$*"; }
dockerrunuw() { eval dockerrunu --volume "$(pwd)":"$(pwd)" --workdir "$(pwd)" "$*"; }

docker-logs() {
docker logs -f "$(docker ps | fzf | awk '{print $1}')"
}

alias dc='docker compose'
alias dcd='docker compose down --remove-orphans'
alias podman-nuke='podman rm -f'
alias podman-machine-restart='podman machine stop; sleep 3; podman machine start'

++ podman machine list --format "{{range .}}{{.Name}}\t{{.VMType}}\t{{.LastUp}}\n{{end -}}" | rg running

alias babellint='dockerrunuw ghcr.io/heussd/babellint:main'


# Cloud
#alias az='dockerrun -v ${HOME}/.azure/:/root/.azure -v ${HOME}/.kube/:/root/.kube/ -v ${HOME}/.ssh:/root/.ssh mcr.microsoft.com/azure-cli az'
#alias aws='docker run --rm -it --volume "$(pwd)":"$(pwd)" --workdir "$(pwd)" -v ~/.aws:/root/.aws amazon/aws-cli'
#alias kubectl='dockerrunu -v ${HOME}/.kube/:/.kube bitnami/kubectl:latest'
#alias gcloud='docker run --rm -ti --volumes-from gcloud-config google/cloud-sdk gcloud'

# Office
alias reveal-md='docker run --rm -p 1948:1948 -v $(pwd)/:/slides webpronl/reveal-md:latest'

#alias pandoc='dockerrunuw pandoc/latex:latest' # Use native command as pipes work differently
#alias latex='dockerrunu --net=none -v "$PWD":/data "blang/latex:ubuntu"'
#alias latexmk='latex latexmk'
#alias graphviz="graphviz/graphviz:ubuntu-20.04"

# Development tools
alias protoc='dockerrunu -v $(pwd):$(pwd) -w $(pwd) znly/protoc'

#alias mvn='dockerrunuw --volume "$HOME/.m2":/root/.m2 maven:3-jdk-11 mvn'
#alias gradle='dockerrunuw gradle gradle'
#alias ruby='dockerrunuw ruby:latest ruby'

# Taken from https://github.com/JanGalek/dockerized/tree/master/applications/node
#alias node='docker run --rm --interactive --tty --volume $PWD:/app -w /app --user $(id -u):$(id -g) node node '
#alias npm='docker run --rm --interactive --tty --volume $PWD:/usr/src/app -w /usr/src/app --user $(id -u):$(id -g) node npm --loglevel=warn '
#alias npx='docker run --rm --interactive --tty --volume $PWD:/app -w /app --user $(id -u):$(id -g) node npx --loglevel=warn '
#alias node10='dockerrunu --volume "$(pwd):/app" -w /app node:10'
#alias npm10='node10 npm --loglevel=warn '
#alias npx10='node10 npx --loglevel=warn '

# git {{{

alias g.cherry-pick="git cherry-pick"
alias g.reset_hard='git reset --hard'

alias g.fetch='git pull'
alias g.merge='git merge'
alias g.bisect='git bisect'


alias gb='git branch'

alias gc='git commit --verbose'
alias 'gc!'='git commit --verbose --amend'
alias gcs='git commit --gpg-sign'
alias 'gcs!'='git commit --verbose --gpg-sign --amend'
alias gcss='git commit --gpg-sign --signoff'
alias 'gcss!'='git commit --verbose --gpg-sign --signoff --amend'

alias gcb='git checkout -b'
alias gco='git checkout'
alias gcor='git checkout --recurse-submodules'

alias gcl='git clone --recurse-submodules'

alias gd='git diff'
alias gds='git diff --staged'

alias gf='git fetch'
alias gfa='git fetch --all --prune --jobs=10'

alias gl='git pull'

alias gp='git remote \
  | xargs -I R git push R "$(git_current_branch)"'
alias gpa='git remote \
  | xargs -I R git push R --all'
alias gpat='git remote \
  | xargs -I R git push R --all && git remote \
  | xargs -I R git push R --tags'
alias 'gpfat!'='git remote \
  | xargs -I R git push R --all --force && git remote \
  | xargs -I R git push R --tags --force'
alias 'gpf!'='git remote \
  | xargs -I R git push R --all --force'
alias gpoat='echo "Deprecated, use gpat"'
alias 'gpoat!'='echo "Deprecated, use gpfat!"'

alias grb='git rebase'
alias grba='git rebase --abort'
alias grbc='git rebase --continue'

alias gm='git merge'
alias gma='git merge --abort'
alias gmc='git merge --continue'

alias gsb='git status --short --branch'

alias gts='git tag --sign'
# }}}
