CHANNEL=$(shell bash conf-tool.sh read CHANNEL)
ENV=$(shell bash conf-tool.sh read ENV)
DEVICE_IP=$(shell bash conf-tool.sh read DEVICE_IP)
DEVICE_USERNAME=$(shell bash conf-tool.sh read DEVICE_USERNAME)
DEVICE_PORT=$(shell bash conf-tool.sh read DEVICE_PORT)
USER_KEY=$(shell bash conf-tool.sh read USER_KEY)
USER_EMAIL=$(shell bash conf-tool.sh read USER_EMAIL)

all: .config

.config:
	bash conf-tool.sh
	echo "Please re-run the command"
	exit 2

clean:
	rm -rf *.img *.model *.manifest snaps

%.model: boards/%.yaml # sign a model file
	cat definition.yaml $< | node json2yaml.js | sed "s|TIMESTAMP|$(shell date -Iseconds --utc)|g" | snap sign -k "$(USER_KEY)" > $@
snaps/%: deps/%.yaml
	node build-tool.js --env $(ENV) --channel $(CHANNEL) --board $*
.cloud-init.yaml: $(ENV).cloud-init.yaml
	cat $(ENV).cloud-init.yaml | USER_EMAIL=$(USER_EMAIL) envsubst > .cloud-init.yaml
%.img: %.model snaps/% .cloud-init.yaml # build an image
	sudo ubuntu-image snap -o $@ --cloud-init $(ENV).cloud-init.yaml -c $(CHANNEL) $<

# VM stuff

vm.img: amd64.img # make a copy of the newest clean image
	cp amd64.img vm.img
start: vm.img # launch the image with kvm
	kvm -smp 2 -m 1500 -netdev user,id=mynet0,hostfwd=tcp::8022-:22,hostfwd=tcp::8090-:80 -device virtio-net-pci,netdev=mynet0 -drive file=vm.img,format=raw
ssh: # ssh into it (don't check the key because that one changes after every rebuild)
	ssh $(DEVICE_USERNAME)@$(DEVICE_IP) -p $(DEVICE_PORT) -o StrictHostKeyChecking=no -o GlobalKnownHostsFile=/dev/null -o UserKnownHostsFile=/dev/null
