body() {
    IFS= read -r header
    printf '%s\n' "$header"
    "$@"
}

col() {
	awk "{ print \$$1; }"
}

mp4() {
	ffmpeg -i "$1" -vcodec copy -acodec ac3 "${1%.*}.mp4"
}

safedir() {
	echo "$@ $(pwd)" | md5sum | cut -b-32
}

diffWith() {
	diffCmd=$@
	diffFile="/tmp/diffwith-$(safedir $diffCmd).patch"
	$diffCmd > $diffFile
	dos2unix -q $diffFile
	( gvim -f $diffFile ; rm $diffFile ) &
}

showimage() {
	(
		local pkg
		pkg=$1
		pkg="${pkg:=*/*}"
		cd /var/tmp/portage/$pkg-*/image || return 1
		find . -not -type d -print0 | xargs -0r ls -lvhF --color=auto
		du -shc */*
	)
}

cov() {
	local cov=/tmp/cov.$$
	local all=$cov/all
	local key=$cov/key
	local html=$cov/html
	local htmlfin=bin/cov
	local gcov=$(which $(build $@ -qand1 variant=coverage | grep -w compile | \
			sed -n "s/.*\/gcc-\([0-9]\+\.[0-9]\+\.[0-9]\+\)\/.*/gcov-\1/p" | head -n1))
	if [[ ! -x $gcov ]] ; then
		echo "Couldn't find a suitable gcov"
		return 1
	fi
	echo "Using $gcov"

	echo "Removing previous GC notes and runs"
	lcov -z -d .
	find -path */coverage/*.run -delete

	echo "Building $@"
	build $@ -q variant=coverage || return 2

	echo "Extracting coverage data"
	mkdir -p $cov
	lcov -d . -c -o $all --derive-func-data --no-external --rc geninfo_auto_base=1 -q --gcov-tool $gcov || return 3
	lcov --remove $all "*/bin/*" -o $key -q || return 4

	echo "Generating HTML"
	mkdir -p $html
	genhtml $key -o $html -s -k -t . --demangle-cpp --sort --function-coverage -q --num-spaces=2 || return 5
	rsync -a --delete-after $html/ $htmlfin/
	rm -rf $cov

	xdotool search --name LCOV windowactivate --sync key F5 windowactivate $(xdotool getactivewindow) || \
		xdg-open "file://$(realpath $htmlfin)/index.html"
	echo "Done"
}

sizes() {
	find -path */release/* -type f -perm -111 -delete
	build variant=release
	find -path */release/* -type f -perm -111 | sort | xargs -r strip --strip-unneeded
	find -path */release/* -type f -perm -111 -printf "%p\t%s\n" | sort -k1 | \
			column -N path,size -R path,size -t -s $'\t' | tee ~/new
}

PATH="/usr/lib/ccache/bin:$PATH"
CORES=$(grep core\ id /proc/cpuinfo | sort -u | wc -l)
CPUS=$(grep core\ id /proc/cpuinfo -c)
if [ -n "$DISTCC_HOSTS" ] ; then
	TASKS=$(echo $DISTCC_HOSTS | tr ' ' '\n' | cut -d / -f2 | paste -s -d+  | bc)
elif [ -x /usr/bin/distcc ] ; then
	TASKS=$(distcc -j)
else
	TASKS=$((($CORES + $CPUS) / 2))
fi
export FEATURES="ccache"
alias :e="gvim"
alias d="cd ~/dev"
alias p="cd ~/dev/portage"
alias ChuckNorris="sudo"
alias l="/bin/ls -NlhvF --color"
alias grep="/bin/grep -I --color=auto --exclude-dir=node_modules --exclude-dir=CVS --exclude-dir=.git --exclude-dir=.svn --exclude-dir=bin --exclude=tags --exclude-dir=docs/html --exclude-dir=target --exclude-dir=.idea --exclude=*.iml"
alias emerge-state='watch "( ps -C sandbox -o stime,cmd ; tail /var/log/emerge.log /var/tmp/portage/*/*/temp/build.log 2> /dev/null )"'
alias df="/bin/df -hT"
title() {
	echo -ne "\033]0;$@\007"
}
vg() {
	valgrind \
		--show-leak-kinds=all \
		--suppressions=$HOME/dev/valgrind.suppressions \
		--leak-check=full \
		--log-file=/var/tmp/vg.log \
		$@
}
build() {
	title "Build in progress"
	CCACHE_BASEDIR=$(git root) nice -n5 b2 -j$TASKS $@
	rtn=$?
	if [ $rtn -eq 0 ]; then
		title "✔ ${PWD/#$HOME/\~} $@"
	else
		title "✘ ${PWD/#$HOME/\~} $@"
	fi
	return $rtn
}
onchange() {
	$@
	while inotifywait -qr . --exclude '/bin/|\.sw.|/target/|/\.git/|\.gcov' -e modify ; do
		clear
		printf '\e[3J'
		$@
	done
}
autobuild() {
	onchange build $@
}
autocov() {
	onchange cov . 0
}
# CVS
cvsd() {
	diffWith "cvs diff -wubB $@"
}
# SVN
svnd() {
	diffWith "svn diff --force --no-diff-deleted -x -b $@"
}
# Git
gitd() {
	diffWith "git diff --no-prefix --relative -b -M $@"
}
gitdc() {
	diffWith "git diff --cached --no-prefix --relative -b -M $@"
}
gppdmb() {
	PARENT=${1:-master}
	git checkout $PARENT && git pull --prune && git delete-merged-branches
}
createAllBranches() {
	for branch in $(git branch --all | grep '^\s*remotes' | egrep --invert-match '(:?HEAD|master)$'); do git branch --track "${branch#*/*/}" "$branch"; done
}
filterAllBranches() {
	git filter-branch --subdirectory-filter $1 --prune-empty --tag-name-filter cat -d /tmp/$$ -- $(git branch | cut -b 3-)
}
alias gst='git status'
# Hg
hgd() {
	diffWith "hg diff -p -b $@"
}

if [ "$(awk '$5=="/" {print $1}' </proc/1/mountinfo)" != "$(awk '$5=="/" {print $1}' </proc/$$/mountinfo)" ]; then
	# chroot
	if [ -e /etc/redhat-release ]; then
		ROOT=$(cat /etc/redhat-release)
	elif [ -e /etc/gentoo-release ]; then
		ROOT=$(cat /etc/gentoo-release)
	else
		ROOT="unknown chroot"
	fi
	PS1='\[\033[01;32m\]$ROOT \[\033[01;34m\]\w \$\[\033[00m\] '
	PROMPT_COMMAND='echo -ne "\033]0;${PWD/#$HOME/\~} ($ROOT)\007"'
elif [ -z "$SSH_CONNECTION" ] ; then
	# local
	PS1='\[\033[01;34m\]\w \$\[\033[00m\] '
	PROMPT_COMMAND='echo -ne "\033]0;${PWD/#$HOME/\~}\007"'
else
	# ssh
	PS1='\[\033[01;32m\]\h \[\033[01;34m\]\w \$\[\033[00m\] '
	PROMPT_COMMAND='echo -ne "\033]0;${PWD/#$HOME/\~} ($HOSTNAME)\007"'
fi
PATH=$PATH:~/files/scripts/

export XAUTHORITY=~/.Xauthority
export HISTFILESIZE=15000
export HISTSIZE=${HISTFILESIZE}
export HISTCONTROL=ignoredups:ignorespace
shopt -s histappend
export LESSCHARSET=utf-8
if [[ -n $DISPLAY ]]; then
	export EDITOR="gvim -f"
else
	export EDITOR="vim"
fi
shopt -s cdspell
shopt -s checkwinsize
shopt -s no_empty_cmd_completion

[ -x /usr/bin/fuck ] && eval $(thefuck --alias)

if [ -x /usr/bin/hh ] ; then
	export HSTR_CONFIG=hicolor,raw-history-view
	export PROMPT_COMMAND="history -a; history -n; ${PROMPT_COMMAND}"
	if [[ $- =~ .*i.* ]]; then bind '"\C-r": "\C-a hh -- \C-j"'; fi
fi