#!/bin/sh

if [ ! -r .git/origin ]; then
        echo "not in git repo" 2>&1
        exit 1
fi

origin=($(cat .git/origin))

prot=rsync,git
prot0=rsync://
prot1=git://
sep=/
if [ "${origin[2]}" == "ssh" ]; then
    prot=ssh
    prot0=
    prot1=
    sep=:
fi

path=${origin[0]}${sep}${origin[1]}

echo "[ $prot://$path ]"

rm -rf .git/tmp-refs/

if ! rsync -avz ${prot0}${path}/refs/ .git/tmp-refs/; then
	echo "rsync of refs failed" 2>&1
	exit 1
fi

args=""

for i in .git/tmp-refs/heads/*; do
	branch=$(basename "$i")
	args+=" +$branch:$branch"
done

if ! git-fetch -u -f ${prot1}${path} $args; then
	echo "git-fetch failed" 2>&1
	exit 1
fi

rm -rf .git/old-refs
mv -f .git/refs .git/old-refs
mv -f .git/tmp-refs .git/refs

