#!/bin/bash

# Script to maintain a (target) tree based on the main kernel
# Author: Amit Kucheria (amit@ubuntu.com)
# Date: 11/07/08

# Modified for netbook use
# Andy Whitcroft <apw@canonical.com>

# Modified for netbook-lpia branch
# Steve Conklin <sconklin@canonical.com>

# Assumptions:
#  1. Every rebase during devel-cycle is an ABI bump
#  2. The target tree's patches are always on top
#  3. As a consequence of 2., tags are not really useful
#  4. autogenerated patches are marked with AUTO; others are marked with SAUCE
#  5. Keep things in a state that they can be merged back
#     into the main tree at the end of the dev cycle

CurBase=$(git log --pretty=oneline --grep="UBUNTU: Ubuntu-2.6.24" -1 | \
		cut -d' ' -f3-)
CurBranch=$(git branch|awk '/^\*/{print $2}')

if [ "$1" = "" ]; then
	echo "Usage: $(basename $0) <tag in master branch to rebase on>"

	NewBase=$(git log --pretty=oneline --grep="UBUNTU: Ubuntu-2.6.24" \
		-1 master|cut -d' ' -f3-)
	echo
	echo "Last base seems to be $CurBase"
	echo "The latest master release is $NewBase"
	exit 1
else
	remoteTag="$1"
fi
if [ "$(git tag -l $remoteTag 2>/dev/null)" = "" ]; then
	echo "ERROR: $remoteTag does not seem to be a valid tag!" >&2
	exit 1
fi

rebasing=".git/rebase-apply"

# Configuration variables
release="ubuntu"
basever=`sed -n '1s/^.*(\(.*\)-.*).*$/\1/p' debian/changelog`
patchDir=./patches
# masterTree=git://zinc.ubuntu.com/ubuntu/ubuntu-$release.git

# Find the base of the tree, and extract branch specific prefix.
baseCommit=$(git log --pretty=format:'%H %s' \
	`git merge-base origin/master HEAD`..HEAD | \
	awk '/UBUNTU: '".*-Ubuntu-$basever-0.0"'$/ { print $1 " " $NF }'
)
baseHash="${baseCommit% *}"
basePrefix="${baseCommit#* }"
basePrefix="${basePrefix%%-*}"

baseTag="$basePrefix-Ubuntu-$basever-0.0"

if [ "$baseHash" = "" -o "$basePrefix" = "" ]; then
	echo "$0: base commit not found -- aborting" 1>&2
	exit 1
fi

#echo "baseHash<$baseHash> basePrefix<$basePrefix> baseTag<$baseTag>"
#exit 0

remoteBranch=auto-tmp-remote
git=`which git`

rm -rf .patches "$patchDir"
mkdir -p $patchDir
rm -rf "$rebasing/"

echo "* Check for uncommitted files..."
$git status | grep -q "nothing to commit"
if [ ! $? -eq "0" ]; then
	echo "\tUncommitted changes found!\n\tClean out your tree before running this script. Exiting."
	exit 1;
fi

##echo "\n"
##echo "* Checking out master tree..."
##$git checkout origin/netbook
##$git reset --hard

echo "\n"
echo "* Exporting current work as patches..."
$git format-patch -o $patchDir $baseHash
# Deleting tags is evil...
#$git tag -l | grep "Ubuntu-2.6.2*" | xargs $git tag -d
#$git tag -l | grep "Ubuntu-LPIA-2.6.2*" | xargs $git tag -d

### Debugging
##mkdir -p .patches
##cp $patchDir/*.patch .patches
### end Debugging

echo "* Cleaning up patches..."
# Remove auto-generated patches
find $patchDir -type f -name "*UBUNTU-AUTO*" -print0 | xargs -0 rm -f

# Remove updates to debian/control, debian/control.stub and di/kernel-versions
for i in "$patchDir"/*.patch
do
	echo "$i ..."
	awk '
		BEGIN						{ on=1 }
		/^diff --git a\/debian\/control /		{ on=0; next }
		/^diff --git a\/debian\/control.stub /		{ on=0; next }
		/^diff --git a\/debian\/d-i\/kernel-versions /	{ on=0; next }
		/^diff /					{ on=1 }
		(on == 1)					{ print }
	' <"$i" >"$i.new"
	mv "$i.new" "$i"
	# If the patch is now empty just remove it.
	if ! grep '^diff ' "$i" >/dev/null; then
		rm -f "$i"
	fi
done

echo "\n"
echo "* Starting rebase"
$git branch -D $remoteBranch
$git checkout -b $remoteBranch $remoteTag

# Disable all git hooks
$git config --bool ubuntu.flavour-changes-ok true
$git config --bool ubuntu.allow-non-sauce-commit true
$git config --bool ubuntu.others-changes-ok true

# Mark our base point on the tree.
echo "AUTO #0"
$git commit --allow-empty -s -m "UBUNTU: $baseTag"

# Delete upstream ABI, extra arch/flavours
echo "AUTO #3"
$git rm -r debian/abi/\*
$git rm -r debian/config/\*
$git rm debian/control.d/vars.generic debian/control.d/vars.server
$git rm debian/rules.d/amd64.mk debian/rules.d/i386.mk
$git commit -a -s -m "UBUNTU: AUTO: Delete unncessary ABI/arch/flavours"
$git status

# Disable all git hooks
$git config --bool ubuntu.flavour-changes-ok true
$git config --bool ubuntu.allow-non-sauce-commit true
$git config --bool ubuntu.others-changes-ok true

# Start new changelog
echo "AUTO #4"
$git mv debian/changelog debian/changelog.$release
DEBFULLNAME="Ubuntu Kernel Team" \
DEBEMAIL="kernel-team@lists.ubuntu.com" \
	EDITOR=: dch --create --package linux --newversion $basever-0.0

# Need to change timestamp else patches fail -- use the timestamp of the first
# entry from the main changelog.
ts_current=`tail -n1 debian/changelog | sed 's/.*>  \(.*\)$/\1/'`
ts_desired=`tail -n1 debian/changelog.$release | sed 's/.*>  \(.*\)$/\1/'`
sed -i -e "s/${ts_current}/${ts_desired}/" debian/changelog

currAbi=`head -n1 debian/changelog.$release | sed 's/.*('"$basever"'-\(.*\)\..*).*$$/\1/'`
sed -i -e "s/$basever-${currAbi}/$basever-1/g" debian/control.stub
sed -i -e "s/$basever-${currAbi}/$basever-1/g" debian/control
sed -i -e "s/$basever-${currAbi}/$basever-1/g" debian/d-i/kernel-versions
$git add debian/changelog debian/control.stub debian/control debian/d-i/kernel-versions
$git commit -a -s -m "UBUNTU: AUTO: Start new changelog and revert to known abi"
$git status

# Apply pending patches
$git am -C0 patches/*
if [ -d "$rebasing/" ]; then
    echo "\tFailed to apply patches"
    echo "\tPlease fix the patches on branch $remoteBranch and then sync to the master branch"
    exit 1;
fi

echo ""
echo "If the final result looks good, then do the following to make it permanent:"
##echo " * Run debian/scripts/misc/retag-branch to retag"
echo " * git checkout $CurBranch"
echo " * git reset --hard $remoteBranch"
echo
echo "Some hints to progress (ONLY HINTS! DON'T TRUST ULTIMATELY!)"
echo " * Start a new release (if you did not before)"
echo " * ./debian/scripts/misc/insert-ubuntu-changes debian/changelog " \
	$(echo $CurBase|cut -d- -f3) $(echo $remoteTag|cut -d- -f3)
echo " * git add debian/changelog"
echo " * git commit -s -m \"UBUNTU: Rebased to $(echo $remoteTag|cut -d- -f2-)\""
echo " * Add any other changes you want to have in that release"
echo " * Insert the changes into the changelog and commit that"
echo " * Note: Make sure the commit tag is UBUNTU: NBK-Ubuntu-2.6.24-..."

exit 0

echo " * rm -rf patches/"

