env:
	$(eval ACCOUNT_ID=$(shell aws iam get-user | jq -r '.User.Arn' | egrep -o '\d+'))
	$(eval REPO_NAME=$(shell aws cloudformation describe-stack-resource --stack-name shared-resources --logical-resource-id BuildDockerRepo | jq -r '.StackResourceDetail.PhysicalResourceId'))
	$(eval REGION=$(shell aws configure get region))
	$(eval S3_BUCKET=$(shell aws cloudformation describe-stack-resource --stack-name shared-resources --logical-resource-id BuildArtifacts | jq -r '.StackResourceDetail.PhysicalResourceId'))
	@echo 'export REPOSITORY_URI=${ACCOUNT_ID}.dkr.ecr.${REGION}.amazonaws.com/${REPO_NAME}'
	@echo 'export S3_BUCKET=${S3_BUCKET}'

cfn-build:
	aws cloudformation update-stack \
		--stack-name shared-resources \
		--capabilities CAPABILITY_IAM \
		--template-body file://config/cloudformation/build.yaml

cfn-iam:
	aws cloudformation update-stack \
		--stack-name iam \
		--capabilities CAPABILITY_NAMED_IAM \
		--template-body file://config/cloudformation/iam.yaml

cfn-compute:
	aws cloudformation update-stack \
		--stack-name shared-compute \
		--capabilities CAPABILITY_IAM \
		--template-body file://config/cloudformation/compute.yaml

docker-build:
	mkdir -p build/docker
	cp docker/Dockerfile build/docker/
	@eval $(shell aws ecr get-login); \
	cd build/docker; \
		docker build -t ${REPOSITORY_URI}:latest .; \
		docker push ${REPOSITORY_URI}:latest

compile:
	GOOS=linux GOARCH=amd64 go build -o build/serverless/bin/encrypt lambda/encrypt/encrypt.go

build: compile

package: build
	cp config/cloudformation/encrypt.yaml build/serverless/
	cd build/serverless && aws cloudformation package \
		--template-file encrypt.yaml \
		--s3-bucket ${S3_BUILD_ARTIFACTS} \
		--s3-prefix encrypt \
		--output-template-file transformed.yaml

deploy: package
	aws cloudformation deploy \
		--stack-name encrypt \
		--template-file build/serverless/transformed.yaml \
		--capabilities CAPABILITY_IAM
