#!/bin/bash
set -e

# This script cleans the experimental pool for the apt repo.
# This is useful when there are a lot of old experimental debs and you only want to keep the most recent.
#

: ${DOCKER_RELEASE_DIR:=$DEST}
APTDIR=$DOCKER_RELEASE_DIR/apt/repo/pool/experimental
: ${DOCKER_ARCHIVE_DIR:=$DEST/archive}
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

latest_versions=$(dpkg-scanpackages "$APTDIR" /dev/null 2>/dev/null | awk -F ': ' '$1 == "Filename" { print $2 }')

# get the latest version
latest_docker_engine_file=$(echo "$latest_versions" | grep docker-engine)
latest_docker_engine_version=$(basename ${latest_docker_engine_file%~*})

echo "latest docker-engine version: $latest_docker_engine_version"

# remove all the files that are not that version in experimental
pool_dir=$(dirname "$latest_docker_engine_file")
old_pkgs=( $(ls "$pool_dir" | grep -v "^${latest_docker_engine_version}" | grep "${latest_docker_engine_version%%~git*}") )

echo "${old_pkgs[@]}"

mkdir -p "$DOCKER_ARCHIVE_DIR"
for old_pkg in "${old_pkgs[@]}"; do
	echo "moving ${pool_dir}/${old_pkg} to $DOCKER_ARCHIVE_DIR"
	mv "${pool_dir}/${old_pkg}" "$DOCKER_ARCHIVE_DIR"
done

echo
echo "$pool_dir now has contents:"
ls "$pool_dir"

# now regenerate release files for experimental
export COMPONENT=experimental
source "${DIR}/update-apt-repo"

echo "You will now want to: "
echo "   - re-sign the repo with hack/make/sign-repo"
echo "   - re-generate index files with hack/make/generate-index-listing"
