PROJECT = cadvisor
DOCKER_TAG ?= $(PROJECT)-${USER}
VERSION ?= master
# Extracted src directory
SRC_DIR = src/$(PROJECT)-$(subst v,,$(VERSION))
# Multi-arch targets are generated from this
TARGETS = cadvisor-amd64 cadvisor-arm cadvisor-arm64

# Default make target will run tests
.DEFAULT_GOAL = build

.PHONY: test
test:
	@echo "no tests"

# Build all static Minitor binaries
.PHONY: all
all: $(TARGETS)

$(SRC_DIR):
	mkdir -p ./src
	git clone --depth=1 --branch $(VERSION) https://github.com/google/cadvisor.git $(SRC_DIR)

.PHONY: clean
clean:
	rm -f ./src

.PHONY: build
build: $(SRC_DIR)
	./build.sh "$(DOCKER_TAG)" "$(SRC_DIR)"

## Multi-arch targets
$(TARGETS): $(SRC_DIR)
	GOARCH=$(lastword $(subst -, ,$(@))) \
		   ./build.sh "$(DOCKER_TAG)" "$(SRC_DIR)"
    
.PHONY: docker-build-env
docker-build-env: $(SRC_DIR)
	docker build -f Dockerfile.build-env . -t $(DOCKER_TAG)-build-env

.PHONY: build-in-docker
build-in-docker: docker-build-env
	docker run --rm \
		-v $(shell pwd)/$(SRC_DIR):/go/src/github.com/google/cadvisor \
		-e GOARCH=amd64 \
		$(DOCKER_TAG)-build-env \
		make build \
		&& cp $(SRC_DIR)/$(PROJECT) ./$(PROJECT)-amd64

.PHONY: build-in-docker-arm
build-in-docker-arm: docker-build-env
	docker run --rm \
		-v $(shell pwd)/$(SRC_DIR):/go/src/github.com/google/cadvisor \
		-e GOARCH=arm \
		$(DOCKER_TAG)-build-env \
		make build \
		&& cp $(SRC_DIR)/$(PROJECT) ./$(PROJECT)-arm

.PHONY: build-in-docker-arm64
build-in-docker-arm64: docker-build-env
	docker run --rm \
		-v $(shell pwd)/$(SRC_DIR):/go/src/github.com/google/cadvisor \
		-e GOARCH=arm64 \
		$(DOCKER_TAG)-build-env \
		make build \
		&& cp $(SRC_DIR)/$(PROJECT) ./$(PROJECT)-arm64

# Arch specific docker build targets
.PHONY: docker-build
docker-build: cadvisor-amd64
	docker build . -t ${DOCKER_TAG}

.PHONY: docker-build-arm
docker-build-arm: cadvisor-arm
	docker build \
		--build-arg REPO=arm32v7 \
		--build-arg GOARCH=arm\
		. -t ${DOCKER_TAG}-arm

.PHONY: docker-build-arm64
docker-build-arm64: cadvisor-arm64
	docker build \
		--build-arg REPO=arm64v8 \
		--build-arg GOARCH=arm64 \
		. -t ${DOCKER_TAG}-arm64