#!/bin/bash
set -e

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

imagePrefix=
case "$DOCKER_ENGINE_OSARCH" in
	linux/arm)
		imagePrefix='armhf'
		;;
	linux/ppc64le)
		imagePrefix='ppc64le'
		;;
	linux/s390x)
		imagePrefix='s390x'
		;;
esac

if [ "$imagePrefix" ]; then
	for (( i = 0; i < ${#images[@]}; i++ )); do
		images[$i]="$imagePrefix/${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 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:=Dockerfile}" | sh -x
		# Do not use a subshell for the following command. Windows 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 [ "$imagePrefix" ]; then
	for image in "${images[@]}"; do
		target="${image#$imagePrefix/}"
		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
