include .lib/nix/Makefile.make

#
## init
###
.PHONY: build
build:
	nix $(NIX) build -f build \
	 --out-link result \
	 --show-trace $(NIX_BUILD)
	tree result/

init: build
	result/bin/init

#
## vmdk
###
vmdk: var/virtualbox/nixops.vmdk
.PHONY: var/virtualbox/nixops.vmdk

var/virtualbox/nixops.vmdk:
	# NOTE: user's TMPDIR may be too small
	TMPDIR=/tmp \
	time nix $(NIX) build \
	 --out-link var/virtualbox \
	 --argstr system x86_64-linux \
	 -f "<nixpkgs-commonsoft/build/pkgs/installer/nixops-virtualbox>"

#
## create
###
create: $(dir $(NIXOPS_STATE))
	$(if $(filter $(NIXOPS_DEPLOYMENT),$(deployment)),,\
	nixops create \
	 $(NIXOPS_CREATE) \
	 install/logical.nix \
	 install/physical.nix)
modify: $(NIXOPS_STATE)
	nixops modify \
	 $(NIXOPS_MODIFY) \
	 install/logical.nix \
	 install/physical.nix

$(dir $(NIXOPS_STATE)):
	mkdir -p $@

deployment = $(shell \
	test ! -f $(NIXOPS_STATE) || \
	sqlite3 $(NIXOPS_STATE) \
	  "select value from DeploymentAttrs \
	   where name='name' and value='$(NIXOPS_DEPLOYMENT)';")

#
## deploy
###
deploy: create
	time nixops deploy $(NIXOPS_OPTS) $(NIXOPS_DEPLOY)
	#TMPDIR=/tmp \
	#time disnixos-env --use-nixops \
	# -s install/disnix/services.nix \
	# -d install/disnix/distribution.nix \
	# -n install/logical.nix \
	# -n install/physical.nix
%/offline: NIX_BUILD+=--option substituters ""
%/offline: NIXOPS_DEPLOY+=--option substituters ""
%/offline: %
	
%/verbose: NIX+=-v -v -v
%/verbose: %
	

stop:
	nixops stop

#
## state
###
state: $(NIXOPS_STATE)
	sqlite3 $(NIXOPS_STATE) .dump

privateIpv4:
	sqlite3 $(NIXOPS_STATE) \
	 'update ResourceAttrs set value = "$(IPv4)" where name="privateIpv4"'