#!/bin/sh

set -e

PREFIX=/usr/local/bin
GIT=$PREFIX/git
DARCS=$PREFIX/darcs

[ -d _darcs -a -d .git ] || exit 1

TMPDIR=/tmp/git2darcs
[ -d $TMPDIR -a -w $TMPDIR ] || mkdir -p $TMPDIR || exit 1

HEAD=`$GIT rev-list --no-walk --pretty=%H HEAD | tail -1`

# Nur fast-forward kompatible commits ziehen,
# um keine Konflikte ins darcs zu recorden.
# Im laufenden Betrieb muss der master branch
# des git upstreams also "sauber" bleiben.
# XXX Fehlermeldung per mail o.dgl. hinter das git pull bauen.

$GIT pull --ff-only --all

FETCH_HEAD=`$GIT rev-list --no-walk --pretty=%H FETCH_HEAD | tail -1`

[ -n "$HEAD" -a -n "$FETCH_HEAD" ] && [ "$HEAD" = "$FETCH_HEAD" ] && exit 0

NEW_COMMITS="$HEAD..$FETCH_HEAD"

$GIT rev-list --reverse --no-walk "$NEW_COMMITS" > $TMPDIR/rev-list

[ -s $TMPDIR/rev-list ]
sed -n -E -e 's@^(.+)$@'"$GIT"' reset --hard \1 \&\& '"$GIT"' rev-list --no-walk --pretty=\"%s%n%-b%n%ad %H\" \1 \| tail +2 > '"$TMPDIR/body"' \&\& '"$GIT"' rev-list --no-walk --pretty=format:\"'"$DARCS"' record --all --look-for-adds --logfile='"$TMPDIR/body"' --author \\\"%an <%ae>\\\"\" \1 | tail +2 > '"$TMPDIR/git2darcs.darcs.sh"' \&\& sh '"$TMPDIR/git2darcs.darcs.sh"'@p' $TMPDIR/rev-list > $TMPDIR/git2darcs.sh
sh $TMPDIR/git2darcs.sh

rm -rf $TMPDIR
