#!/bin/bash
set -e

# image list should match what's in the Dockerfile (minus the explicit images IDs)
images=(
	buildpack-deps:jessie
	busybox:latest
	debian:jessie
	hello-world:latest
)

if [ "$TEST_IMAGE_NAMESPACE" ]; then
	for (( i = 0; i < ${#images[@]}; i++ )); do
		images[$i]="$TEST_IMAGE_NAMESPACE/${images[$i]}"
	done
fi

if ! docker inspect "${images[@]}" &> /dev/null; then
	hardCodedDir='/docker-frozen-images'
	if [ -d "$hardCodedDir" ]; then
		# Do not use a subshell for the following command. Windows to Linux CI
		# runs bash 3.x so will not trap an error in a subshell.
		# http://stackoverflow.com/questions/22630363/how-does-set-e-work-with-subshells
		set -x; tar -cC "$hardCodedDir" . | docker load; set +x
	else
		dir="$DEST/frozen-images"
		# extract the exact "RUN download-frozen-image-v2.sh" line from the Dockerfile itself for consistency
		# NOTE: this will fail if either "curl" or "jq" is not installed or if the Dockerfile is not available/readable
		awk '
			$1 == "RUN" && $2 == "./contrib/download-frozen-image-v2.sh" {
				for (i = 2; i < NF; i++)
					printf ( $i == "'"$hardCodedDir"'" ? "'"$dir"'" : $i ) " ";
				print $NF;
				if (/\\$/) {
					inCont = 1;
					next;
				}
			}
			inCont {
				print;
				if (!/\\$/) {
					inCont = 0;
				}
			}
		' "$DOCKERFILE" | sh -x
		# Do not use a subshell for the following command. Windows to Linux CI
		# runs bash 3.x so will not trap an error in a subshell.
		# http://stackoverflow.com/questions/22630363/how-does-set-e-work-with-subshells
		set -x; tar -cC "$dir" . | docker load; set +x
	fi
fi

if [ "$TEST_IMAGE_NAMESPACE" ]; then
	for image in "${images[@]}"; do
		target="${image#$TEST_IMAGE_NAMESPACE/}"
		if [ "$target" != "$image" ]; then
			# tag images to ensure that all integrations work with the defined image names
			docker tag "$image" "$target"
			# then remove original tags as these make problems with later tests (e.g., TestInspectApiImageResponse)
			docker rmi "$image"
		fi
	done
fi

# explicitly rename "hello-world:latest" to ":frozen" for the test that uses it
docker tag hello-world:latest hello-world:frozen
docker rmi hello-world:latest
