#!/bin/zsh

# vim: ft=zsh
# Unix
# short for ls
alias l="ls"
# just like l but a single column
alias l1="l -1"
# full long list with permissions, size, ownership etc
alias ll="l -l"
# just like ll but with git status
alias llg="ll --git"
# sorts the list by created date asc, so that the latest file is closer to the
# prompt
alias llc="ll --sort=created"
# use eza instead of system ls
alias ls="eza -gahF --icons --group-directories-first"
alias ln="ln -v"
alias mkdir="mkdir -p"
alias rm='trash'
alias rmf='trash'
alias rmrf='trash'
alias less='less -r'
alias du="ncdu --color dark -rr -x --exclude .git --exclude node_modules"

alias tf='terraform'
alias tfa='terraform apply'
alias tfd='terraform destroy'

# check internet connection
alias chkint='pingf kagi.com'

# just like l but with git status
alias lg="lazygit"

# postgres
# --------
#
# Temporary Postgres Instance
alias pgtmp='docker run --rm -p 5432:5432 -e POSTGRES_PASSWORD=password -e POSTGRES_HOST_AUTH_METHOD=trust -v$(pwd)/tmp/pgdata:/var/lib/postgresql/data postgres:alpine'

# remove .orig files created after `git mergetool` is run
alias rmorig='rm $(fd --hidden "\.orig")'

# pulumi
alias p='pulumi'

# Jira
# transition issue
# jt() {
#   jira i "$(jira i | fzf | awk '{ print $1 }')" -t
# }

alias tree="erd -I --hidden --no-git --dir-order last --layout inverted --sort name --human --no-ignore"
alias gtree="erd -I --hidden --no-git --dir-order last --layout inverted --sort name --human"
# tree paged
treep ()
{
  tree --color=force "$@" | bat -p
}

# gtree paged
gtreep ()
{
  gtree --color=force "$@" | bat -p
}

# Bundler
alias b="bundle"

# SSH fix for working with xterm-color256-italic
alias ssh="TERM=xterm-256color ssh"

# You-Get
alias yg='you-get'

# Rails
alias migrate="be rails db:migrate db:rollback && be rails db:migrate"
alias s="rspec"
alias rof="rspec --only-failures"
alias be='bundle exec'

# Pretty print the path
alias path='echo $PATH | tr -s ":" "\n"'

# git reset empty files
gref() {
  command git --no-pager diff --cached --stat | command grep " |\\s*0$" | awk '{system("command git reset " $1)}'
}

# Git
alias gnap='git add -N . && gap && gref'
alias gcd1='git clone --depth=1'
# alias gprune='gf --prune && git branch -r | awk "{print \$1}" | grep -E -v -f /dev/fd/0 <(git branch -vv | grep origin) | awk "{print \$1}" | xargs git branch -D'
alias gclone='git clone'
# list all branches in a git bundle
alias gblh='git bundle list-heads'
# first commit sha
alias gfc='git rev-list --max-parents=0 HEAD'
# stash aliases
alias gsu='git stash -u'
alias gsp='git stash pop'
alias gsa='git stash --all'

fork() {
  repo_name=$(echo "$1" | xargs basename | cut -d. -f1)
  clone_path="${HOME%/}/dev/forks/${repo_name}"
  echo "Repo will be cloned to ${clone_path}"
  git clone "$1" "${clone_path}"
  cd "${clone_path}" || return
}

# returns the first sha matching the selected branch
# this is useful when rebasing the branch to it's base to clean up things.
#
# git rebase -i $(base_sha)
base_sha() {
  git fetch
  branch=$(git branch --format='%(refname:short)' | fzf)
  git show-ref refs/heads/"${branch}" | awk '{ print $1 }'
}

# automate git fixup workflow with interactive fzf selection
# assumes staged files are part of the fixup and a clean working directory for
# the reabse
gfixup() {
  branch=$(git branch --format='%(refname:short)' | fzf)
  commit_sha=$(git log "${branch}.." --pretty=oneline --color=always | fzf | awk '{ print $1 }')
  git fixup "${commit_sha}"
  # there's probably a better way of doing this.. but good enough for now. This
  # will try to stash unrelated changes, and pop them afterwards while avoiding
  # a pop when a stash was not performed. Stashing is necessary because a rebase
  # requires a clean working tree
  if git stash -u | grep -q 'No local changes to save'; then
    git rebase -i "${commit_sha}~1"
  else
    git rebase -i "${commit_sha}~1"
    git stash pop
  fi
}

# better git tree log:
alias gg='git log --graph --abbrev-commit --decorate --format=format:'\''%C(bold green)%h%C(reset) - %C(bold blue)%ai%C(reset) %C(bold red)%an%C(reset) %C(bold yellow)%d%C(reset)'\'\'' %C(dim white)- %s%C(reset)'\'

# fuzzy commands with fzf
alias gcorb='gco --track $(git branch -r  --format="%(refname:short)" | fzf --prompt="Select remote branch to checkout: ")'
alias gcob='gco $(git branch --format="%(refname:short)" | fzf --prompt="Select branch to checkout: ")'
alias vfz='vim $(fz)'
alias preview="fzf --preview 'bat --color \"always\" --line-range 0:30 {}'"
alias fta='tmux attach -t $(tl | fzf | tr ":" "\n" | head -n1)'
alias ftk='tmux kill-session -t $(tl | fzf | tr ":" "\n" | head -n1)'
alias fcd='cd $(fd --type d --exclude node_modules --exclude vendor --exclude build --exclude _build --exclude bundle --exclude Godeps | fzf)'

# network utils
alias flushdns='sudo dscacheutil -flushcache && sudo killall -HUP mDNSResponder && echo cache flushed'

localip() {
  ifconfig en0 | rg 'inet ' | awk '{print $2}'
}

# Usage: hr freethousand [port]
#
# Summary: Kill a process that is listening a port
#
# Help: Don't know where that Rails server is listening? Just freethousand!
# This command takes a port as an argument, otherwise defaulting to 3000.
freethousand() {
  port="${1:-3000}"
  pid="$(lsof -t -i tcp:"${port}")"

  if [ -n "${pid}" ]; then
    echo "Killing process with PID ${pid} listening on port ${port}..." >&2
    kill "${pid}"
  else
    echo "No process listening on port ${port}" >&2
  fi
}

alias vim='nvim'
alias vi='nvim'
alias vimdiff='nvim -d'
alias legacyvim='command vim'
# vim scratch - doesn't prompt to save a file on exit. Great for quick
# experiments and iterations on configs
alias vsc="nvim -c 'set buftype=nofile'"

# HomeBrew
alias brewup='brew upgrade'
# Search installed packages usage brewg lsusb
alias brewg='brew list | rg'

alias d='cd ~/dev'
alias dl='cd ~/Downloads'
alias f='cd ~/dev/forks'
alias dt='cd ~/dotfiles'
alias dots='cd ~/dotfiles'
alias hcd='cd ~/dev/hashrocket'
alias blog='cd ~/dev/sites/DorianKarter.com/blog'
alias docs='cd ~/Dropbox/Documents'

alias ss='imgur-screenshot.sh'

# debian
# creates a pbcopy command using xclip
command -v xclip >/dev/null && alias pbcopy='xclip -sel c'

# parse + highlight help for cli tools
# usage: help <command>
# example: help git commit
# 
# You can also use the alias h
# example: h git commit
help() {
    "$@" --help 2>&1 | bat --plain --language=help
}
alias h='help'

alias lolcat='lolcrab'

# quick config
alias vimconfig='vim -o ~/.vimrc ~/.vimrc.bundles'
alias muxconfig='vim ~/.config/tmux/tmux.conf && tmux source-file ~/.config/tmux/tmux.conf'
alias sshconfig='vim ~/.ssh/config'
alias aliasconfig='vim ~/.aliases && source ~/.aliases'
alias hostsconfig='sudo nvim /etc/hosts'
alias zshconfig="vim -o ~/.zshrc && source ~/.zshrc"
alias gitconfig="vim ~/.gitconfig"
alias kittyconfig="vim ~/.config/kitty/kitty.conf"
alias vifmconfig="vim ~/.config/vifm/vifmrc"

# tmux
alias mux='airmux'
# tmux new
tn() {
  tmux new -s "$(basename "${PWD}")"
}

# session manager using sesh + fzf
# https://github.com/joshmedeski/sesh
# the awk seen part filters out duplicates without affecting the sorting - this
# was needed since starting to use smug
t() {
  # shellcheck disable=SC2312
  sesh connect "$(sesh list --icons | awk '!seen[$0]++' | fzf-tmux -p)"
}

# tmux attach
alias ta='tmux attach -t'

# ripgrep - rg is taken by rails generate alias from the oh-my-zsh rails plugin
alias rgrep='command rg'

# rails
alias twiki='be rails db:migrate && be rails db:rollback && be rails db:migrate && be rails db:test:prepare'
alias dtp='be rails db:test:prepare'

# elixir
alias extwiki='mix ecto.migrate && mix ecto.rollback && mix ecto.migrate'
alias imix='iex -S mix'
alias im='iex -S mix'
alias mc='mix compile'
# mix compile check
alias mcc='mix compile --force --all-warnings --warnings-as-errors'
alias mpr='mix phx.routes'
alias mps='mix phx.server'
alias mt='mix test'
# resets the test database
alias mtr='MIX_ENV=test mix ecto.drop'
alias mdg='mix deps.get'
alias mdca='mix deps.clean --all'
alias ecto.reset='mix ecto.drop && mix ecto.create && mix ecto.migrate && mix ecto.seed'

mix_cmd_app() {
  mix cmd --app "$1" mix
}
#  execute commands on umbrella apps
alias ma='mix_cmd_app'

# KEEP AT BOTTOM TO ALLOW OVERRIDE
# Include machine specific aliases

# [ -f ~/.aliases.local ] && . ~/.aliases.local
