RM_F = rm -f

DOCKER = docker
NIX_DOCKER_0 = $(DOCKER) run --rm --volume $$(pwd):$$(pwd) --workdir $$(pwd)
NIX_DOCKER_MAINT = $(NIX_DOCKER_0) --mount source=type=volume,source=nix,target=/nix2 nixos/nix
NIX_DOCKER = $(NIX_DOCKER_0) --mount source=type=volume,source=nix,target=/nix nixos/nix

NIX_BUILD = $(NIX_DOCKER) nix-build
NIX_BUILD_OUT = $(NIX_DOCKER) sh -c '$$(nix-build)'

IMAGES = mailcow nano nextcloud prosody samba vim webcron
IMAGES_BIN = $(patsubst %,%.bin,$(IMAGES))
IMAGES_LOAD = $(patsubst %,%.load,$(IMAGES))

.PHONY: all images clean init gc update #$(IMAGES_LOAD)

all: images

# Deletes all build artifacts.
clean:
	$(RM_F) $(IMAGES_BIN)

# Runs nix-collect-garbage in the Docker container.
gc:
	$(NIX_DOCKER) nix-collect-garbage

# Initializes the Docker volume with a Nix store.
#
# Run this before any other target of this makefile.
init:
	$(NIX_DOCKER_MAINT) sh -c 'nix-env -iA nixpkgs.rsync && rsync --info=progress2 -a /nix/ /nix2/'

update:
	$(NIX_DOCKER) sh -c 'nix-channel --update'

# Builds and loads all known Docker images.
images: $(IMAGES_LOAD)

# The following approaches were all considered and discarded:
#
# Takes ~240 seconds (nextcloud image):
#
#%.load: images.nix
#	$(NIX_DOCKER) sh -c '$$(nix-build --no-out-link images.nix -A $(patsubst %.load,%,$@).streamed)' | $(DOCKER) load
#   
# Takes ~60 seconds (nextcloud image):
#
#%.load: images.nix
#	$(NIX_DOCKER) sh -c 'cat $$(nix-build --no-out-link images.nix -A $(patsubst %.load,%,$@).layered)' | $(DOCKER) load
#
# The final approach takes ~20 seconds to build the nextcloud image.

# Builds a Docker image as a .bin file that you can load with 'docker
# load'.
%.bin: images.nix
	$(NIX_DOCKER) sh -c 'cp $$(nix-build --no-out-link images.nix -A $(patsubst %.bin,%,$@).layered) $@'

# Builds and loads a Docker image into your local Docker daemon.
%.load: %.bin
	$(DOCKER) load --input=$<
