#!/bin/bash
set -e

# This script updates the apt repo in $DOCKER_RELEASE_DIR/apt/repo.
# This script is a "fix all" for any sort of problems that might have occurred with
# the Release or Package files in the repo.
# It should only be used in the rare case of extreme emergencies to regenerate
# Release and Package files for the apt repo.
#
# NOTE: Always be sure to re-sign the repo with hack/make/sign-repos after running
# this script.

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

# supported arches/sections
arches=( amd64 i386 )

# Preserve existing components but don't add any non-existing ones
for component in main testing experimental ; do
	if ls "$APTDIR/dists/*/$component" >/dev/null 2>&1 ; then
		components+=( $component )
	fi
done

dists=( $(find "${APTDIR}/dists" -maxdepth 1 -mindepth 1 -type d) )

# override component if it is set
if [ "$COMPONENT" ]; then
	components=( $COMPONENT )
fi

# release the debs
for version in "${dists[@]}"; do
	for component in "${components[@]}"; do
		codename="${version//debootstrap-}"

		# update the filelist for this codename/component
		find "$APTDIR/pool/$component" \
			-name *~${codename#*-}*.deb > "$APTDIR/dists/$codename/$component/filelist"
	done
done

# run the apt-ftparchive commands so we can have pinning
apt-ftparchive generate "$APTDIR/conf/apt-ftparchive.conf"

for dist in "${dists[@]}"; do
	version=$(basename "$dist")
	for component in "${components[@]}"; do
		codename="${version//debootstrap-}"

		apt-ftparchive \
			-o "APT::FTPArchive::Release::Codename=$codename" \
			-o "APT::FTPArchive::Release::Suite=$codename" \
			-c "$APTDIR/conf/docker-engine-release.conf" \
			release \
			"$APTDIR/dists/$codename" > "$APTDIR/dists/$codename/Release"

		for arch in "${arches[@]}"; do
			apt-ftparchive \
				-o "APT::FTPArchive::Release::Codename=$codename" \
				-o "APT::FTPArchive::Release::Suite=$codename" \
				-o "APT::FTPArchive::Release::Component=$component" \
				-o "APT::FTPArchive::Release::Architecture=$arch" \
				-c "$APTDIR/conf/docker-engine-release.conf" \
				release \
				"$APTDIR/dists/$codename/$component/binary-$arch" > "$APTDIR/dists/$codename/$component/binary-$arch/Release"
		done
	done
done
