IMAGE_TAG ?= $(shell git describe --always)

.PHONY: FORCE

DOCKER := docker

all:
	$(MAKE) web
	$(MAKE) docker
	$(MAKE) push

docker:
	$(DOCKER) build -t emblem:$(IMAGE_TAG) .

push:
	for tag in $(IMAGE_TAG) $(CI_COMMIT_BRANCH); do \
		$(DOCKER) tag emblem:$(IMAGE_TAG) registry.gitlab.com/euphon/emblem:$(IMAGE_TAG) &&\
		$(DOCKER) push registry.gitlab.com/euphon/emblem:$(IMAGE_TAG); \
	done

docker-run:
	$(DOCKER) build --network=host -t emblem:$(IMAGE_TAG) .
	$(DOCKER) run -ti --rm -p 12345:80 emblem:$(IMAGE_TAG)

web: FORCE
	cd web; npm run build

test:
	cd api; ./manage.py migrate
	cd api; ./manage.py test tests

stress:
	cd api; ./manage.py test tests.stress

deploy: deploy-dev deploy-prod

deploy-dev: FORCE
	./scripts/deploy --kubeconfig deploy/kubeconfig.derby \
	  --db-host postgres-postgresql.db \
	  --emblem-env dev \
	  -n emblem \
	  -i registry.gitlab.com/euphon/emblem:$(IMAGE_TAG)

deploy-g: FORCE
	./scripts/deploy --kubeconfig deploy/kubeconfig.g \
	  --db-host 10.42.0.1 \
	  --emblem-env prod \
	  -n emblem \
	  -i registry.gitlab.com/euphon/emblem:$(IMAGE_TAG)

deploy-prod: FORCE
	./scripts/deploy --kubeconfig deploy/kubeconfig.themblem \
	  --db-host 192.168.33.175 \
	  --emblem-env prod \
	  -n emblem \
	  -i registry.gitlab.com/euphon/emblem:$(IMAGE_TAG)
run:
	./scripts/run-tmux.sh

vm: FORCE vm/sys.img $(DATA_IMGS)
	q q +vblk:vm/sys.img +sd:vm/ext.img -f --no-net -- \
		-bios /usr/share/ovmf/OVMF.fd \
		-serial stdio \
		-device virtio-blk,drive=sys \
		-netdev user,id=n0,hostfwd=::10022-:22,hostfwd=::6006-:6006,hostfwd=::13000-:3000,hostfwd=::18000-:8000 \
		-device virtio-net-pci,netdev=n0 \
		$(shell for i in 0 1 2 3 4 5 6 7 8; do echo -drive file=vm/data-$$i.img,if=none,id=d$$i -device nvme,serial=NVME_$$i,drive=d$$i; done) \
		-device virtio-scsi \
		-drive file=$(EXT_IMG),if=none,id=ext0 -device scsi-hd,drive=ext0
