.PHONY: help all install lint clean test deploy integration-test delete

ifdef $(env)
	include environments/$(env).env
endif

CFN         := cloudformation
CFN_NAME    := example-cloud-function
BUCKET      := $(shell aws s3 ls | grep templates | cut -c 24-)
TEST_DATA   := 100
TEST_RESULT := "2,4,5,10,20,25,50"
EMAIL       := "cv@juancanham.com"

help:
	@echo  'Targets:'
	@echo  ' * all [install clean lint test deploy integration-test]'
	@echo  ' * delete'
	@echo  '   - optionally you can specify an env to load overrides'

all: install clean lint test deploy integration-test

install:
	pip install -r requirements.txt

clean:
	rm -f */**/*.pyc
	rm -f $(CFN)/.*-generated.yaml
	rm -f test-response.txt

lint:
	yamllint .
	black .
	pylint --disable line-too-long src/ tests/
	cfn-lint $(CFN)/*.yaml
	shellcheck ci/*.sh

test:
	pytest 

deploy:
	aws cloudformation package \
		--template-file $(CFN)/lambda-sam-template.yaml \
		--s3-bucket $(BUCKET) \
		--output-template-file $(CFN)/.$(CFN_NAME)-generated.yaml

	aws cloudformation deploy \
		--stack-name $(CFN_NAME) \
		--template-file $(CFN)/.$(CFN_NAME)-generated.yaml \
		--capabilities CAPABILITY_IAM \
		--parameter-overrides \
			NotificationEmail=$(EMAIL) \
			TestData=$(TEST_DATA) \
			TestExpected=$(TEST_RESULT)

delete:
	aws cloudformation delete-stack --stack-name $(CFN_NAME)

integration-test:
	aws lambda invoke \
		--payload $(TEST_DATA)
		--log-type Tail \
		--function-name $$(aws cloudformation describe-stacks \
			--stack-name $(CFN_NAME) \
			--output text \
			--query 'Stacks[0].Outputs[?OutputKey==`LambdaArn`].OutputValue' \
		) \
		test-response.txt
	grep $(TEST_RESULT) test-response.txt