#!/bin/sh
#The files in this directory (except pbuilderrc) were written by
#(C) 2006 Kapil Hari Paranjape <kapil@imsc.res.in>. 
#They are placed in the public domain. You can do with them exactly as you wish.

# This assumes:
# A.
#	You have added the following lines to you ~/.pbuilderrc
#		BASEDEV=<path to your base device>
#		COWDEV=<path to your cow device>
#
# B.
#        That the BASE and COW device have been properly set up.
#        Specifically, you must run:
#		e2fsck -f $BASEDEV
#	 It is too painful to run this everytime!
#
#	 You can also run
#		blockdev --setro $BASEDEV
#	 This tries to ensure that the $BASDEV remains pristine.
#
# C.
#	 It also assumes that /dev/mapper/{total,work}
#	 do not exist already.


if [ $# -lt 1 ]
then
	echo You need to supply the name of the dsc file
	exit 1
fi

PKGDSC=$1

# Source the pbuilderrc file
. /usr/lib/pbuilder/pbuilder-loadconfig


if [ -z "$BASEDEV" -o -z "$COWDEV" ]
then
	echo Please define BASEDEV and COWDEV in your ~/.pbuilderrc file
	exit 1
fi

# Size computations

BASESIZE=$(blockdev --getsize $BASEDEV)
COWSIZE=$(blockdev --getsize $COWDEV)
TOTAL=$[ $COWSIZE + $BASESIZE ]

## Create the total base device
# It consists of the base device extended by zeroes.
# The length of the zeroes is the size of the cow.
dd if=/dev/zero of=$COWDEV bs=4K count=16

( echo 0 $BASESIZE linear $BASEDEV 0 ; \
  echo $BASESIZE $COWSIZE zero ) | \
  dmsetup create total 

## Create the work device
# It is the snapshot device with the all writes
# going to the cow device. The file-system is resized
# to the maximum extent possible.
echo 0 $TOTAL snapshot /dev/mapper/total $COWDEV p 16 | \
  dmsetup create work

resize2fs /dev/mapper/work 

mount /dev/mapper/work $BUILDPLACE

# run build
pbuilder build --no-targz $PKGDSC 

## Check the status
# If pbuilder returned with
# an error then we must stop
# and be able to examine the work space.
[ $? != 0 ] && \
( echo Error during build. $BUILDPLACE contains the build place. ; \
  exit 1 )

## Clean Up
umount $BUILDPLACE
dmsetup remove work
dmsetup remove total

echo Done.

