#!/bin/sh

export PATH=$PATH:/home/dwmw2/cogito

STAGINGLOCK=/staging/upload.lock
STAGE=/staging/dwmw2/snapshot-2.6
FINAL=/pub/linux/kernel/v2.6/snapshots

cd /home/dwmw2/git/snapshot-2.6

cg-update origin || exit 1

RELNAME=`cg-tag-ls | grep -v 'git' | tail -n1 | cut -f1 | sed s/^v//`
RELCOMM=`cg-tag-ls | grep -v 'git' | tail -n1 | cut -f2`
SNAPNAME=`cg-tag-ls | grep -- "$RELNAME-git" | tail -n1 | cut -f1 | sed s/^v//`
SNAPCOMM=`cg-tag-ls | grep -- "$RELNAME-git" | tail -n1 | cut -f2`
CURCOMM=`cat .git/HEAD`

echo release  $RELNAME $RELCOMM
echo lastsnap $SNAPNAME $SNAPCOMM 
echo head $CURCOMM

[ "$SNAPCOMM" == "$CURCOMM" ] && exit 0


if [ "$SNAPNAME" == "" ]; then
	CURNAME="$RELNAME-git1"
else
	OLDGITNUM=`echo $SNAPNAME | sed s/^.*-git//`
	NEWGITNUM=`expr $OLDGITNUM + 1`
	CURNAME="$RELNAME-git$NEWGITNUM"
fi


#echo newsnap  $CURNAME $CURCOMM

CURTREE=$CURCOMM
RELTREE=`git-cat-file tag $RELCOMM | head -n1 | cut -f2 -d' '`

EXTRAVERSION=-`echo $CURNAME | cut -f2- -d-`

perl -pi -e "s/EXTRAVERSION =.*/EXTRAVERSION = $EXTRAVERSION/" Makefile
cg-diff Makefile > $STAGE/tmppatch-extraver
checkout-cache -f Makefile

# echo $CURTREE:$RELTREE

# This is, unfortunately, in chronological order. Walking the tree would
# be better.
echo $CURCOMM > $STAGE/patch-$CURNAME.id
cg-log $RELTREE:$CURTREE > $STAGE/patch-$CURNAME.log
cg-diff -r $CURTREE:$RELTREE > $STAGE/tmppatch-$CURNAME-base
combinediff -p1 $STAGE/tmppatch-extraver $STAGE/tmppatch-$CURNAME-base | gzip -9 > $STAGE/patch-$CURNAME.gz
rm $STAGE/tmppatch-extraver $STAGE/tmppatch-$CURNAME-base
cg-tag v$CURNAME $CURCOMM

echo New Snapshot $CURNAME

if [ -r $STAGINGLOCK ]; then
    exec 200< /staging/upload.lock
    flock -s 200
fi

mv -v $STAGE/* $FINAL
