#!/bin/sh

set -e

BZR=${BZR:-bzr}
FORMAT=metadir

if [ $# -ne 2 ]; then
    echo "usage: $0 branchdir repodir" >&2
    exit 1
fi

branchdir=$1
repodir=$2

if [ -d $branchdir/.bzr ]; then
    echo "Can not convert $branchdir when it is itself a branch." >&2
    exit 1
fi
branchdir=`(cd $branchdir && pwd)`

if [ -d $repodir ]; then
    echo "$repodir should not exist" >&2
    exit 1
fi

# get a list of the branches
branches=`(cd $branchdir; find . -name .bzr -exec dirname {} \; -prune | sort)`

# create $repodir
echo "Creating repository at $repodir" >&2
mkdir -p `dirname $repodir` 2>/dev/null || :
$BZR init-repo --format=$FORMAT $repodir
repodir=`(cd $repodir && pwd)`

# for each branch, create a corresponding branch in the repository and pull
# the changes into it.
for branch in $branches; do
    mkdir -p $repodir/`dirname $branch` 2>/dev/null || :
    $BZR init --format=$FORMAT $repodir/$branch
    echo "Converting $branch" >&2
    (cd $repodir/$branch && $BZR pull $branchdir/$branch)
done
