#!/bin/sh

set -x 

case `hostname` in
    hera.kernel.org)
	export PATH=/home/dwmw2/cogito:$PATH
	export BASE_DIRECTORY=/pub/scm/linux/kernel/git/torvalds/linux-2.6.git
	STAGINGLOCK=/staging/upload.lock
	FINAL=/pub/linux/kernel/v2.6/snapshots
	;;
    shinybook.infradead.org)
	export PATH=/shiny/git/git-pasky-base:$PATH
	export BASE_DIRECTORY=/shiny/git/linux-2.6/.git
	unset FINAL
	unset STAGINGLOCK
	;;
    *)
	echo "Unknown host"
	exit 1;
esac

if [ ! -d $BASE_DIRECTORY ]; then
    echo BASE_DIRECTORY $BASE_DIRECTORY not present
    exit 1
fi

export WORK_DIRECTORY=$HOME/snapshots/2.6
export SNAP_TAG_DIRECTORY=$WORK_DIRECTORY/tags
export STAGE=$WORK_DIRECTORY/stage
export SHA1_FILE_DIRECTORY=$BASE_DIRECTORY/objects

# Find 'latest' tag in Linus' tree
# Chronological order is wrong but it'll do for now
RELNAME=`ls -rt $BASE_DIRECTORY/refs/tags/v2.* | tail -n1 | sed "s:$BASE_DIRECTORY/refs/tags/v::" `
RELOBJ=`cat $BASE_DIRECTORY/refs/tags/v$RELNAME`


# Find latest snapshot against that release, if there is one.
SNAPNAME=`ls -rt $SNAP_TAG_DIRECTORY/v$RELNAME-git* | tail -n1 | sed "s:$SNAP_TAG_DIRECTORY/v::" `

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

LASTTREE=`tree-id $LASTOBJ`

CURCOMM=`cat $BASE_DIRECTORY/HEAD`
CURTREE=`tree-id $CURCOMM`
RELTREE=`tree-id $RELOBJ`

echo release $RELNAME commit $RELCOMM tree $RELTREE
echo last `git-cat-file -t $LASTOBJ` $LASTOBJ tree $LASTTREE
echo head $CURCOMM tree $CURTREE

[ "$LASTTREE" == "$CURTREE" ] && exit 0

#echo newsnap  $CURNAME $CURCOMM

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

cd $STAGE || exit 0

rm -rf tmp-empty-tree
mkdir -p tmp-empty-tree/.git
cd tmp-empty-tree

git-read-tree $CURCOMM
git-checkout-cache Makefile
perl -pi -e "s/EXTRAVERSION =.*/EXTRAVERSION = $EXTRAVERSION/" Makefile
git-diff-cache -m -p $RELTREE | gzip -9 > $STAGE/patch-$CURNAME.gz

# This is, unfortunately, in chronological order. Walking the tree would
# be better but we need a heuristic to tell 'local' vs 'remote' branches
echo $CURCOMM > $STAGE/patch-$CURNAME.id
cg-log $RELOBJ:$CURCOMM > $STAGE/patch-$CURNAME.log

echo $CURCOMM > $SNAP_TAG_DIRECTORY/v$CURNAME

echo New Snapshot $CURNAME

[ -z "$FINAL" ] && exit 0

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

mv -v $STAGE/patch-$CURNAME* $FINAL
