GITHASH := $(shell echo ${CODEBUILD_RESOLVED_SOURCE_VERSION} | head -c 8)
VERSION := $(if $(GITHASH),$(GITHASH),"development")

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 sts-${USER} --logical-resource-id DockerRepo | jq -r '.StackResourceDetail.PhysicalResourceId'))
	$(eval REGION=$(shell aws configure get region))
	@echo 'export REPOSITORY_URI=${ACCOUNT_ID}.dkr.ecr.${REGION}.amazonaws.com/${REPO_NAME}'

clean:
	rm -rf build

ensure:
	dep ensure

install: ensure

update:
	dep ensure -update

vet:
	go vet ./...

test:
	go test -cover ./...

configs:
	mkdir -p build
	cp -R config/cloudformation build/cloudformation

compile:
	GOOS=linux GOARCH=amd64 go build -o build/sts src/main.go

build: clean vet test compile configs

docker: cache-bins
	@eval $(shell aws ecr get-login | sed -e "s/-e none//")
	docker build \
		--build-arg srcdir=/go/src/code.justin.tv/vodsvc/sts \
		--tag "${REPOSITORY_URI}:latest" \
		--tag "${REPOSITORY_URI}:${VERSION}" .
	docker push "${REPOSITORY_URI}:latest"
	docker push "${REPOSITORY_URI}:${VERSION}"

cfn:
	aws cloudformation update-stack --stack-name sts-${USER} --template-body file://config/cloudformation/build.yaml

cache-bins:
	bash helper/cache-binaries.sh

publish-bins:
	# convenience target for publishing a new TwitchTranscoder or ffmpeg binary to s3
	# It calculates the md5 hash of the binaries to make builds more efficient.
	$(eval BINARY := TwitchTranscoder)
	$(eval B64MD5 := $(shell openssl md5 -binary $(1) | base64))
	$(eval MD5 := $(shell md5sum $(1) | cut -d' ' -f1))
	aws s3api put-object \
		--bucket vhs.us-west-2.twitch-transcoder \
		--key ${BINARY} \
		--body ${BINARY} \
		--metadata md5=${MD5} \
		--content-md5 ${B64MD5}
