#!/bin/bash
#
# Build Debian and Ubuntu packages from a tarball.
#
# This is the script that our Jenkins/CI system runs. Yes, it is a bit messy.
#
#
# For running this on your own computer (jessie), see https://wiki.debian.org/mk-sbuild
# for information on setting up sbuild.
# Short version: 1) apt-get install ubuntu-dev-tools 2) mk-sbuild jessie
#
# To CHANGE the golden image: sudo schroot -c source:jessie-amd64 -u root
# To ENTER an image snapshot: schroot -c jessie-amd64
# To BUILD within a snapshot: sbuild -A -d jessie-amd64 PACKAGE*.dsc

BINDISTS=${BINDISTS:-jessie}

if [[ -n "${JENKINS_HOME}" ]]; then
	set -x
	if [ "$HOSTNAME" != "cbuild" ]; then
		# Handle old chroot naming on our jenkins servers. Used in the bottom.
		chroot_postfix="-sbuild";
	fi
fi

set -o errexit

. common.sh

rm -rf build
mkdir -p build

SOURCE=$(ls -1 sources/varnish-*.tar.gz)  # XXX
findversion "$SOURCE"

tar xf "${SOURCE}" -C build

# Modify varnish.install to match version
if [ "$V" = "3.0" ] || [ "$V" = "4.0" ] || [ "$V" = "4.1" ]; then
	# Legacy packages don't have separate directory with VCL files
	sed -i "s|^usr/share/varnish/vcl|#usr/share/varnish/vcl|" debian/varnish.install
else
	# Make sure to revert if mangled by older build-job
	sed -i "s|^#usr/share/varnish/vcl|usr/share/varnish/vcl|" debian/varnish.install
fi

cd build/varnish-*

cp -r ../../debian .
rm -f debian/.*.sw?    # Delete any vim temporary files.

ln "../../$SOURCE" "../varnish_$V.$MINOR.orig.tar.gz"

# Modify Section to suit our repository software.
sed -i -e "s|^Section: \([^/]*\)\$|Section: varnish-$V/\1|" debian/control

# Take version override set on Jenkins builds into account.
if [[ -n "${DEBVERSION}" ]]; then
	FULL_VERSION="$V.$MINOR$RELEASE-$DEBVERSION"
	dch -v "$FULL_VERSION" "Release build #$BUILD_NUMBER ID: $BUILD_ID"
else
	FULL_VERSION="$V.$MINOR-0${RELEASE}+daily+$(date +%Y%m%d.%H%M%S)"
	dch -v "$V.$MINOR-0${RELEASE}+daily+$(date +%Y%m%d.%H%M%S)" "Automatic build from git"
fi

dpkg-buildpackage -us -uc -S -j10
cd ..

# By now we are done setting up and building the source package.

if [ "$V" = "3.0" ] || [ "$V" = "4.0" ] || [ "$V" = "4.1" ]; then
	# Build binary packages for the requested releases inside chroots.
	for dist in $BINDISTS; do
		# Legacy packages embedded the release into the package version.
		export DEBIAN_OVERRIDE_BINARY_VERSION="$FULL_VERSION~$dist"
		sbuild -v -A -c "$dist-amd64$chroot_postfix" -d "$dist" varnish_*.dsc
	done
else
	# For 5.0 and onwards there is a single .deb.
	export DEBIAN_OVERRIDE_BINARY_VERSION="$FULL_VERSION"
	sbuild -v -A -c "trusty-amd64$chroot_postfix" -d "trusty" varnish_*.dsc
fi
