#!/bin/sh

mkdir -p "$(git rev-parse --git-dir)/fzf"
history="$(git rev-parse --git-dir)/fzf/history"
null=$(printf "\0")

untracked='/^?? /d'

while test $# != 0
do
	case "$1" in
		(--untracked | -u) untracked="" ;;
	esac
	shift
done

IFS=''
git status --porcelain | sed "$untracked" | while read line
do
	path=$(echo $line | cut -b 4-)
	type=$(echo $line | cut -b -3)
	/bin/echo -e "$type\x00$(basename $path)\x00$path"
done \
	| fzf --multi --with-nth=2 -d '\0' -q "$*" --history=$history \
	--preview='if [ ${1} = "??" ]; then /bin/echo -e "\x1b[32m"; cat {3}; else git diff --color {3}; fi' \
	| cut -d "$null" -f 3-