# We assume we've been checked out into a parallel directory to the
# upstream Fossil trunk sources.
UPSTREAM := ../../trunk

# Get upstream's current commit ID prefix to use as a unique version
# tag for our builds.  Note that it isn't *our* commit ID we care about:
# when someone compares these versions on our Docker Hub page to those
# of Fossil, they don't want to bounce through the indirection of this
# repo's version numbering scheme.
FSLVER := $(shell cut -c1-12 < $(UPSTREAM)/manifest.uuid)
FSLREL := $(shell cd $(UPSTREAM) ; fossil tag ls | grep -E 'version-\d' | tail -1)

# The list of platforms we build the container for.  It should cover 99%
# of all practical use cases.  It's split so we do native ARM CPU builds
# locally and x86 elsewhere, so we don't take the QEMU speed hit of
# cross-compilation.  Bonus: we roughly double our build cores.
ARM_PLATFORMS := linux/arm64,linux/arm/v7
X86_PLATFORMS := linux/amd64,linux/386
X86_BUILD_HOST := x86
BUILDER := fossil-addons-builder

# Image repo prefix to use for "push"
REPOUSER=tangentsoft
TAGPFX=$(REPOUSER)/

# Create container image.  Without options, creates a local
# tip-of-trunk build.
all: build
	docker build \
		--platform $(ARM_PLATFORMS),$(X86_PLATFORMS) \
		--builder $(BUILDER) \
		--build-arg UID=1000 \
		--build-arg FSLVER=$(FSLVER) \
		--tag $(TAGPFX)fossil:$(FSLVER) \
		--tag $(TAGPFX)fossil:latest \
		$(DBFLAGS) $(UPSTREAM)

# Create the build container if it doesn't exist already.  Without
# this, we can't create multi-arch containers.  If you don't need that,
# you can revert to "docker build".
build:
	@if ! docker buildx inspect $(BUILDER) > /dev/null 2>&1 ; then \
		docker buildx create \
			--name $(BUILDER) \
			--platform $(ARM_PLATFORMS) ; \
		docker buildx create \
			--append \
			--name $(BUILDER) \
			--platform $(X86_PLATFORMS) \
			ssh://$(USER)@$(X86_BUILD_HOST) ; \
	fi
	docker buildx inspect \
		--bootstrap \
		--builder $(BUILDER) ; \

login:
	docker login --username $(REPOUSER) docker.io

# Custom version of "all" for pushing the built image up to Docker Hub
push: all
	$(MAKE) DBFLAGS=--push 

# Alternative to "push" for making release images
release: build
	cd ../../release ; fossil update release
	$(MAKE) \
		DBFLAGS=--push \
		FSLVER=$(FSLREL) \
		UPSTREAM=../../release
