#!/bin/sh

set -e

refname="$1"
OLDHEAD="$2"
NEWHEAD="$3"
NEW_COMMITS="$OLDHEAD..$NEWHEAD"

WD=/home/ffdo/public_html/wiki
G2D=$WD/wikidata-ffdo
LOCK=$WD/git2darcs.lockf
TMPDIR=/tmp/git2darcs.$USER

PREFIX=/usr/local/bin
GIT="$PREFIX/git --git-dir $G2D/.git"
DARCS=$PREFIX/darcs

cd $G2D

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

[ -d $TMPDIR -a -w $TMPDIR ] || mkdir -p $TMPDIR || exit 1

lockf -t 10 $LOCK sh -x << -EOF-

set -e

cd $G2D

export LANG=de_DE.UTF-8
export LC_ALL=de_DE.UTF-8

# Nur fast-forward kompatible commits ziehen, d.h. akzeptieren -
# (git pull --ff-only --all)
# aber wie kann man das hier (bei push) sicherstellen?

[ -n "$OLDHEAD" -a -n "$NEWHEAD" ] && [ "$OLDHEAD" = "$NEWHEAD" ] && exit 0

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

[ -s $TMPDIR/rev-list ] || { rm -rf $TMPDIR ; exit 0 ; }

sed -n -E -e 's@^(.+)\$@cd $G2D \&\& '"$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 -x $TMPDIR/git2darcs.sh

$DARCS push --all

rm -rf $TMPDIR

-EOF-
