# If not running interactively, don't do anything
case $- in
	*i*) ;;
	*) return;;
esac

# Some stuff shouldn't be in this file
[ -e ~/.bash_secrets ] && source ~/.bash_secrets

# Default stuff
export EDITOR=nvim

# Color config and aliases
alias ls='ls -G'
alias grep='grep --color=auto'
alias fgrep='fgrep --color=auto'
alias emacs='emacs -nw'

# Aliases
alias vim=nvim
alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'
alias rcp='rsync -Lh --progress'
alias gdiff='diff -urN --color=always'
alias gcomm='git log | head -n 1'
alias ffcount='ffprobe -v error -select_streams v:0 -count_packets -show_entries stream=nb_read_packets -of csv=p=0'
alias ffres='ffprobe -v error -select_streams v:0 -show_entries stream=width,height -of csv=s=x:p=0'

# Copy stdin to clipboard
cbcopy() {
	if [ "$(uname)" = "Darwin" ]; then
		pbcopy
	elif [ -z "$WAYLAND_DISPLAY" ]; then
		sed -z '$ s/\n$//' | xclip -i -selection clipboard
	else
		sed -z '$ s/\n$//' | wl-copy
	fi
}

# Get clipboard data
cbget() {
	if [ "$(uname)" = "Darwin" ]; then
		pbpaste
	elif [ -z "$WAYLAND_DISPLAY" ]; then
		xclip -o -selection clipboard
	else
		wl-paste
	fi
}

# Upload to p.mort.coffee
bin() {
	if [ -z "$1" ]; then
		curl --silent --upload-file - https://p.mort.coffee | tee >(cbcopy)
	else
		curl --silent --upload-file "$1" https://p.mort.coffee | tee >(cbcopy)
	fi
}

# Create a temp dir, spawn a shell there, delete when done
tmp() {
	local dir="$(mktemp -d "/tmp/$USER.tmp.XXXXXXXX")"
	(cd "$dir"; $SHELL)
	rm -rf "$dir"
}

# Make .. go up once, ... up twice, etc
dots() {
	for _ in $(seq 1 $1); do
		cd ..
	done
}
dots_acc="."
for i in $(seq 1 10); do
	dots_acc="$dots_acc."
	alias "$dots_acc"="dots $i"
done

# Go up, until the cwd ends with "$1"
to() {
	if [ -z "$1" ]; then
		echo "Usage: $0 <path fragment>"
		return 1
	fi

	if ! pwd | grep "$1/" >/dev/null; then
		echo "$1: not in the cwd"
		return 1
	fi

	while :; do
		wd="$(pwd)"

		# 'pwd' never seems to return paths with multiple successive slashes,
		# so checking if "$1//" is contained in "$wd//" is a "reliable" way to
		# check if "$wd" ends with "$1" using only posix sh.
		if [ "$wd" = "/" ] || printf "%s" "$wd//" | grep "$1//" >/dev/null; then
			return
		fi
		cd ..
	done
}

# Completion
autoload -Uz compinit && compinit
zstyle ':completion:*' matcher-list 'm:{a-z}={A-Za-z}'
zstyle ':completion:*' menu yes select

# Keys
bindkey -e

# Options
unsetopt BEEP

# Add Go
export PATH="/usr/lib/go-1.13/bin:$HOME/go/bin:$HOME/.cargo/bin:$HOME/.local/bin:$PATH"

# Load cargo
[ -e "$HOME/.cargo/env" ] && source "$HOME/.cargo/env"

##
# Prompt
##

autoload -U colors && colors
setopt PROMPT_SUBST

PS1='$(starstruck --zsh -e $?)'

# This should be the last part.
if [ -e "$HOME/.bashrc-local" ]; then
	source "$HOME/.bashrc-local"
fi

# If anything appears below this line, move it to .bashrc-local.
