#!/bin/sh

if ! GITDIR=$(git rev-parse --git-dir) ; then
    echo "Not in a git repository" >&2
    exit 0
fi

TREE=$(dirname $GITDIR)

cd $TREE

if [ -d .git/annex ] ; then
    echo "In an annex repository"
    git annex sync
    exit
fi

[ -e pre-sync ] && sh pre-sync
git stash push -m "SYNC SAVE"
git pull --all

[ -e mid-sync ] && sh mid-sync

TEMP=$(mktemp)
git branch -r | cut -d'/' -f2- > "${TEMP}"
git branch --merged | grep -vFf "${TEMP}" | xargs git branch -d
rm "${TEMP}"

git push --all origin
[ -e post-sync ] && sh post-sync
if git stash list | head -n1 | grep "SYNC SAVE" >/dev/null ; then
    git stash pop
fi
