
# 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 rmrf='rm -rf'
# rmrf_() {
#   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" || return; $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
dif() { colordiff -u "$@" | less; }
# mkcd() { mkdir "$1" && cd "$1"; }
# ct() {
#   if [ $# -eq 0 ]; then
#     cd ~/c/tmp
#   elif [[ $# -eq 1 ]]; then
#     if [[ $1 == *.* ]]; then
#       cd ~/c/tmp
#       touch $1
#       $MAIN_EDITOR $1
#     else
#       mkcd ~/c/tmp/$1
#     fi
#   else
#     cd ~/c/tmp
#     eval $@
#   fi
# }
cct() {
  rm -rf ~/c/tmp/myapp* ~/c/tmp/mygem* ~/c/tmp/repro*
  if [ $# -eq 0 ]; then
    if [ ! -d "$PWD" ]; then cd ~/c/tmp || return; fi
  else
    ct "$@"
  fi
}
alias ctt='cct'
alias ctl='ct; llrt'

alias el=elinks
remove_colors() {
  sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g"
}
alias md5sum=md5
alias wcl='wc -l'
alias chx='chmod +x'
ed() { command ed -p '*' "$@"; }
alias wh='which'
alias cmd='command'
# prepend() {
#   text_to_prepend="$1"
#   file=$2
#   tmp_file="tmp_$file"

#   printf '%s\n' "Prepend"
#   printf '%s\n' "$text_to_prepend"
#   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 command -v "$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'

# Kube
# alias kr='kube run'
# krc() { kube run $@ rails c; }
# krb() { kube run $@ bash; }
# kpr() { kube run $@ printenv | sort; }
# krru() { kube run $1 $2 rails runner $3; }
# alias krbg='kube run:bg'
# krrubg() { kube run:bg $1 $2 rails runner $3; }
# alias kl='kube logs'
# alias ke='kube env'
# alias kp='kube pods'

# Apps / Binaries
timer() { sleep $(($1*60)); terminal-notifier -message "${*:2}"; }
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='/sbin/kextunload /System/Library/Extensions/AppleUSBMultitouch.kext' # 2> /dev/null"
alias epad='/sbin/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() {
  local conf=$(awk 'NF > 0 { printf ":" $0 "\\\\n" }' ~/.vimrc.minimal)
  echo $conf | tee >(pbcopy)
}

rails-new() {
  ~/c/boilerplate/rails-template/rails-new "$@"
  if [[ $? -eq 0 && -d "$1" ]]; then cd $1; fi
}
alias rn='rails-new'
gem-new() {
  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\" }"
}
parsecron() {
  ruby -e "require 'cronex'; puts Cronex::ExpressionDescriptor.new('$1').description" \
    | tee >(pbcopy)
}
alias unused='unused -t .tags'

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"'
}


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

export PATH=/opt/homebrew/bin/:$PATH:$HOME/bin

fortune

# set -o vi
stty -ixon
bind -f ~/.inputrc

export EDITOR=/opt/homebrew/bin/nvim
export EDITOR=vim

export HISTIGNORE='pwd:exit:fg:bg:top:clear:history:ls:ll:uptime:df'
export HISTCONTROL=ignoredups

shopt -s histappend
export HISTSIZE=10000

shopt -s autocd
shopt -s direxpand
shopt -s extglob
# shopt -s nullglob

alias b='bat'
alias bm='bat Makefile'
# bt: bat latest
alias c='cat'
alias cm='cat Makefile'
alias ca='conda activate ama-dev'
alias caa='conda activate atommap-dev'
alias cab='conda activate'
alias cad='conda deactivate'
alias cs='conda activate siflow-dev'
alias cdt='cd `ll |grep ^d |ff NF |fzf`'
alias cdt='cd `command ls -tl |grep ^d |ff NF |fzf`'
# ct: cat latest
alias ct='cat `ls -tp | grep -v / | head -15 |fzf`'
alias cv="networksetup -connectpppoeservice 'NYC VPN'"
alias cx='chmod +x'
alias d='docker'
alias dv="networksetup -disconnectpppoeservice 'NYC VPN'"
alias e=exit
alias fe1='v `ls -tr |tail -7 |fzf`'
alias g='git'
alias gca='git ci -am'
alias glo='g lo'
alias gst='git st'
alias h='head'
alias lc='wc -l'
alias ll="ls -lhtr"
alias l=lt
alias ls="ls -G"
alias lll='ls -1tr'

alias vmsj='vp -p *msj'

# # Enable tab completion
# source ~/.git-completion.bash
# source ~/.gita-completion.bash
# source ~/.tmux-completion.bash
#
# [ -f /usr/local/etc/bash_completion ] && . /usr/local/etc/bash_completion

# colors!
red="\[\033[01;31m\]"
green="\[\033[0;32m\]"
yellow="\[\033[0;33m\]"
blue="\[\033[0;34m\]"
purple="\[\033[0;35m\]"
reset="\[\033[0m\]"

# Change command prompt
# source ~/.git-prompt.sh
export GIT_PS1_SHOWDIRTYSTATE=1
# '\u' adds the name of the current user to the prompt
# '\$(__git_ps1)' adds git-related stuff
# '\W' adds the name of the current directory
export PS1="$yellow\A$green\$(__git_ps1)$blue \W $ $reset"

[ -f ~/.fzf.bash ] && source ~/.fzf.bash

export FZF_DEFAULT_OPTS='--height 40% --layout=reverse --border --multi --info=inline'
#export FZF_DEFAULT_COMMAND='find --type f --exclude .git --follow'
export FZF_DEFAULT_COMMAND='rg --files'

# fe [FUZZY PATTERN] - 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" ]] && ${EDITOR:-vim} -O "${files[@]}" -p
}

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


[ -f "/Users/dzhou/.ghcup/env" ] && source "/Users/dzhou/.ghcup/env" # ghcup-env

# 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
#
take () {
    mkdir -p "$1" && cd "$1"
}

source /Users/nos/.iterm2_shell_integration.bash
export BAT_THEME='Solarized (light)'

# eval "$(register-python-argcomplete conda)"

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

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'

# Prompt


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
}

g() {
    if [[ $# -eq 0 ]]; then
        git status -sb
    else
        git "$@"
    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
}


web() {
    GOLD=$(tput setaf 222)
    GREEN=$(tput setaf 79)
    NC=$(tput sgr0)

    read -ep "$(echo -e "${GOLD}Search ${GREEN}➜ ${NC}")" search_term
    if [[ -n "$search_term" ]]; then
        open "https://search.brave.com/search?q=${search_term}" &>/dev/null
    fi
}

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

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 g="git"
alias gs="git status"
alias gw="git show"
alias gw^="git show HEAD^"
alias gw^^="git show HEAD^^"
alias gw^^^="git show HEAD^^^"
alias gw^^^^="git show HEAD^^^^"
alias gd="git diff HEAD"  # What's changed? Both staged and unstaged.
alias gdo="git diff --cached"  # What's changed? Only staged (added) changes.
# for gco ("git commit only") and gca ("git commit all"), see functions.sh.
# for gget (git clone and cd), see functions.sh.
alias gcaf="git add --all && gcof"
alias gcof="git commit --no-verify -m"
alias gcac="gca Cleanup"
alias gcoc="gco Cleanup"
alias gcaw="gca $'Whitespace\n\n[skip ci]'"
alias gcow="gco $'Whitespace\n\n[skip ci]'"
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.

# Pairing (via https://github.com/barsoom/devbox/blob/master/bin/pair)
alias pairo="pair olle"
alias pairp="pair peter"

# Heroku
alias h="heroku"
alias hdep="git push heroku"
alias hmig="heroku run rake db:migrate"
alias ho="heroku open"
alias hsc="heroku run AUCTIONET_CORE_EMPLOYEE_ID=2 rails console -r heroku"  # Explicit remote, for apps with a staging as well.
alias hscs="heroku run rails console -r staging"
alias hlog="heroku logs -t -r heroku"

# The Stack
alias ssc="dev console prod"
alias sscs="dev console staging"

# WTI (translation service)

# Push to WTI until it sticks.
# It tends to refuse pushes of a target language until it's processed the source language push.
alias wpus="ruby -e 'loop { x = \`wti push; wti push --target\`; puts x; break unless x.include?(%{Locked}); puts; puts %{#{Time.now.strftime(%{%H:%M:%S})}: Retrying in a bit…}; puts; sleep 15 }'"

# 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


# ▛▀▖      ▌        
# ▌ ▌▞▀▖▞▀▖▌▗▘▞▀▖▙▀▖
# ▌ ▌▌ ▌▌ ▖▛▚ ▛▀ ▌  
# ▀▀ ▝▀ ▝▀ ▘ ▘▝▀▘▘  
# -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

case $(uname) in
    Darwin)
        if command -v colima >/dev/null ; then
            alias docker-compose="/opt/homebrew/opt/docker-compose/bin/docker-compose ~/.docker/cli-plugins/docker-compose"
            alias docker-buildx="/opt/homebrew/opt/docker-buildx/bin/docker-buildx ~/.docker/cli-plugins/docker-buildx"
            export DOCKER_HOST="unix://${HOME}/.colima/default/docker.sock"
        else
            return
        fi
        ;;
    Linux)
        alias docker='sudo env -i docker'
        alias docker-compose='sudo env -i docker-compose'
esac

command -v docker >/dev/null || return

# list images/containers
alias {dli,dlsi}='docker images'
alias {dlc,dlsc}='docker container ls -a'

# rm images/containers
alias {drmi,dirm}='docker image rm'
alias {drmc,dcrm}='docker container rm'

alias {dst,dstop}='docker stop'
alias drun='docker run'
alias {drunr,drunrm}='docker run --rm'
alias dps='docker ps'

alias dlogs='docker logs'
alias dexec='docker exec'
alias dshell='docker exec -it /bin/sh'

dprune() {
    docker image prune
    docker volume rm $(docker volume ls -f dangling=true -q)
}

# compose
alias cup='compose up --abort-on-container-exit'
alias cdown='compose down'
alias cbuild='compose build'

dbuild() {
    [ "$1" ] || { >&2 'Usage: dbuild <tag>' ; return 1 ; }
    docker build --tag "$1" .
}

docker_remove_networks() {
    docker network ls | awk '$3 == "bridge" && $2 != "bridge" { print $1 }'
}

dockerkillall() {
    docker stop $(docker ps -a -q)
    docker rm $(docker ps -a -q)
}

DOCKER_NUKE() {
    printf 'This will delete all images and containers, confirm? (y/n): '
    read -r ans
    [ "$ans" = y ] && {
        docker rm $(docker ps -a -q) --force
        docker rmi $(docker images -q) --force
        docker_remove_networks
    }
}


#!/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 '

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

# zsh-specific
# shellcheck disable=SC2154
if [ -n "$ZSH_VERSION" ]; then
	alias -g isotime='$(date -u -Iseconds)'
  timefile() {
    printf '%s%s' "$(date -Iseconds)" ".$1"
  }
	alias -g nnote='$(timefile md)'
	alias -g todaynote='"$(date -u +%Y-%m-%d)"*'
	alias -g detch='&>/dev/null 2>/dev/null & disown'
	alias -g pagit='| $PAGER'
	alias -g w3m-htm='| w3m -T text/html'
	if command -v lolcat >/dev/null; then
		alias -g rofl='| lolcat'
	fi
	alias zpstudy='zpmod source-study | grep -v "[0-5] ms" | sort -bgr'
	alias -g 'wlp'='"$(wl-paste -n)"'
fi

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

# nsenter command to run sh in the namepsace of Docker for Mac xhyve VM: nsenter --target 1 --mount --uts --net --ipc sh
alias enter-docker-vm='docker run -it --rm --privileged --pid=host justincormack/nsenter1'
