NAME ?= dbaas/cicd/actions-runner
DIND_RUNNER_NAME ?= ${NAME}-dind
TAG ?= latest

RUNNER_VERSION ?= 2.280.3
DOCKER_VERSION ?= 20.10.8

TARGETPLATFORM ?= amd64

RUNNER_ECR_REPO="dbaas/cicd/actions-runner"
DIND_ECR_REPO="dbaas/cicd/actions-runner-dind"

RUNNER_VERSION ?= v0.1.1
DIND_VERSION ?= v0.1.0

# default list of platforms for which multiarch image is built
ifeq (${PLATFORMS}, )
	export PLATFORMS="linux/amd64,linux/arm64"
endif

# if IMG_RESULT is unspecified, by default the image will be pushed to registry
ifeq (${IMG_RESULT}, load)
	export PUSH_ARG="--load"
    # if load is specified, image will be built only for the build machine architecture.
    export PLATFORMS="local"
else ifeq (${IMG_RESULT}, cache)
	# if cache is specified, image will only be available in the build cache, it won't be pushed or loaded
	# therefore no PUSH_ARG will be specified
else
	export PUSH_ARG="--push"
endif

ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
ECR_REG="${ACCOUNT_ID}.dkr.ecr.us-west-2.amazonaws.com"

docker-build-ubuntu:
	docker build --build-arg TARGETPLATFORM=${TARGETPLATFORM} --build-arg RUNNER_VERSION=${RUNNER_VERSION} --build-arg DOCKER_VERSION=${DOCKER_VERSION} -t ${NAME}:${TAG} .

docker-build-dind:
	docker build --build-arg TARGETPLATFORM=${TARGETPLATFORM} --build-arg RUNNER_VERSION=${RUNNER_VERSION} --build-arg DOCKER_VERSION=${DOCKER_VERSION} -t ${DIND_RUNNER_NAME}:${TAG} -f Dockerfile.dindrunner .

docker-push-ubuntu:
	if ! aws ecr describe-repositories --repository-name ${RUNNER_ECR_REPO} >/dev/null 2>&1
	then
		aws ecr create-repository --repository-name ${RUNNER_ECR_REPO}
	fi
	aws ecr get-login-password --region us-west-2 | docker login --username AWS --password-stdin ${ECR_REG}
	ECR_IMAGE="${ECR_REG}/${RUNNER_ECR_REPO}:${RUNNER_VERSION}" docker tag ${NAME}:${TAG} ${ECR_IMAGE} \
	&& docker push ${ECR_IMAGE}

docker-push-dind:
	if ! aws ecr describe-repositories --repository-name ${DIND_ECR_REPO} >/dev/null 2>&1
	then
		aws ecr create-repository --repository-name ${DIND_ECR_REPO}
	fi
	aws ecr get-login-password --region us-west-2 | docker login --username AWS --password-stdin ${ECR_REG}
	ECR_IMAGE="${ECR_REG}/${DIND_ECR_REPO}:${DIND_VERSION}" docker tag ${NAME}:${TAG} ${ECR_IMAGE} \
	&& docker push ${ECR_IMAGE}

docker-buildx-ubuntu:
	export DOCKER_CLI_EXPERIMENTAL=enabled
	@if ! docker buildx ls | grep -q container-builder; then\
		docker buildx create --platform ${PLATFORMS} --name container-builder --use;\
	fi
	docker buildx build --platform ${PLATFORMS} \
		--build-arg RUNNER_VERSION=${RUNNER_VERSION} \
		--build-arg DOCKER_VERSION=${DOCKER_VERSION} \
		-t "${NAME}:latest" \
		-f Dockerfile \
		. ${PUSH_ARG}
	docker buildx build --platform ${PLATFORMS} \
		--build-arg RUNNER_VERSION=${RUNNER_VERSION} \
		--build-arg DOCKER_VERSION=${DOCKER_VERSION} \
		-t "${DIND_RUNNER_NAME}:latest" \
		-f Dockerfile.dindrunner \
		. ${PUSH_ARG}
