#!/bin/bash
set -e

# This script creates the apt repos for the .deb files generated by hack/make/build-deb
#
# The following can then be used as apt sources:
# 	deb http://apt.dockerproject.org/repo $distro-$release $version
#
# For example:
#	deb http://apt.dockerproject.org/repo ubuntu-trusy main
#	deb http://apt.dockerproject.org/repo ubuntu-vivid testing
#	deb http://apt.dockerproject.org/repo debian-wheezy experimental
#	deb http://apt.dockerproject.org/repo debian-jessie main
#
# ... and so on and so forth for the builds created by hack/make/build-deb

: ${DOCKER_RELEASE_DIR:=$DEST}
APTDIR=$DOCKER_RELEASE_DIR/apt/repo

# setup the apt repo (if it does not exist)
mkdir -p "$APTDIR/conf" "$APTDIR/db"

# create/update distributions file
for suite in $(exec contrib/reprepro/suites.sh); do
	cat <<-EOF
	Origin: Docker
	Suite: $suite
	Codename: $suite
	Architectures: amd64 i386
	Components: main testing experimental
	Description: Docker APT Repository

	EOF
done > "$APTDIR/conf/distributions"

# set the component and priority for the version being released
component="main"
priority=700

if [[ "$VERSION" == *-rc* ]]; then
	component="testing"
	priority=650
fi

if [ $DOCKER_EXPERIMENTAL ] || [[ "$VERSION" == *-dev ]] || [ -n "$(git status --porcelain)" ]; then
	component="experimental"
	priority=600
fi

# release the debs
for dir in contrib/builder/deb/*/; do
	version="$(basename "$dir")"
	codename="${version//debootstrap-}"

	# add the deb for each component for the distro version with reprepro
	DEBFILE=( "bundles/$VERSION/build-deb/$version/docker-engine"*.deb )

	# if we have a $GPG_PASSPHRASE we may as well
	# dpkg-sign before reprepro
	if [ ! -z "$GPG_PASSPHRASE" ]; then
		dpkg-sig -g "--passphrase $GPG_PASSPHRASE" \
			-k releasedocker --sign builder "${DEBFILE[@]}"
	fi

	reprepro -v --keepunreferencedfiles \
		-S docker-engine -P "$priority" -C "$component" \
		-b "$APTDIR" includedeb "$codename" "${DEBFILE[@]}"
done
