# UID/GID
# UID or GID is the UNIX user ID or group ID of the user who executes
# make. If the UID or GID is not passed as a make variable, an attempt
# is made to determine it.
UID?=$(shell id --user)
GID?=$(shell id --group)

# VERSION
# If no version is specified as a parameter of make, the last git hash
# value is taken.
VERSION:=$(or ${TRAVIS_TAG}, $(shell git rev-parse --short HEAD)-git)

# CONTAINER_RUNTIME
CONTAINER_RUNTIME?=$(shell which docker)

# BUILD_IMAGE
BUILD_IMAGE:=volkerraschek/build-image:latest

# GO ENVIRONMENT
GOARCH?=amd64
GOOS?=linux

# default build
go-build: bindata
	GOOS=${GOOS} \
	GOARCH=${GOARCH} \
		go build -ldflags "-X main.version=${VERSION}"
	chown ${UID}:${GID} ./*

go-test: go-build
	go test -v ./pkg/...

rpm-build: go-build
	rpm-builder \
		--arch x86_64 \
		--compression gzip \
		--exec-file "flucky:/usr/bin/flucky" \
		--file "systemd/flucky.service:/usr/lib/systemd/system/flucky.service" \
		--version ${VERSION} \
		flucky

bindata:
	go-bindata -pkg db -o ./pkg/db/bindataSQL.go ./pkg/db/sql/***
	go-bindata -pkg goldenfiles -o ./test/goldenfiles/bindata.go ./test/goldenfiles/json/***

container-go-build:
	$(MAKE) container-run COMMAND=go-build

container-go-test:
	$(MAKE) container-run COMMAND=go-test

container-rpm-build:
	$(MAKE) container-run COMMAND=rpm-build

container-run:
	${CONTAINER_RUNTIME} run \
		--rm \
		--volume ${PWD}:/workspace \
		${BUILD_IMAGE} \
			make ${COMMAND} \
				UID=${UID} \
				GID=${GID} \
				VERSION=${VERSION} \
				GOOS=${GOOS} \
				GOARCH=${GOARCH}

remote:
	$(MAKE) go-build GOARCH=arm
	scp flucky ${FLUCKY_REMOTE}:/usr/local/bin
	ssh ${FLUCKY_REMOTE} "chmod +x /usr/local/bin/flucky"