# Top-level Makefile for nixos-dev-setup / omni.
#
# Wraps nixos-rebuild + cachix + flake update so common operations are
# one command instead of one paragraph. Adapted from mitchellh's
# Makefile but trimmed:
#
#   - No vm/bootstrap targets — those are handled by `dev-env-bootstrap`
#     for the dev box and by `dev-deploy` for the fleet.
#   - No darwin/wsl targets — we don't run those (yet).
#   - HOST defaults to `hostname` so `make switch` Just Works on the
#     box you're sitting at.
#
# Override anything via env or args:
#
#   make switch HOST=host1
#   make cache CACHE=aiolabs-nix
#   make build FLAKE=/path/to/some/flake

HOST  ?= $(shell hostname)
CACHE ?= aiolabs-nix
FLAKE ?= .

# Always allow unfree — most of our hosts need at least one unfree
# package (e.g. claude-code, vscode). Set in env so child processes
# inherit it (cachix push uses nix-store under the hood).
NIXPKGS_ALLOW_UNFREE := 1
export NIXPKGS_ALLOW_UNFREE

.PHONY: help
help:
	@echo "Usage: make <target> [HOST=<name>] [CACHE=<cache>] [FLAKE=<path>]"
	@echo ""
	@echo "Targets:"
	@echo "  switch         nixos-rebuild switch on the local host"
	@echo "  test           nixos-rebuild test (no boot entry change)"
	@echo "  build          nix build the host's toplevel (no switch)"
	@echo "  update         nix flake update"
	@echo "  cache          push the host's closure to \$$CACHE"
	@echo "  check          nix flake check"
	@echo "  clean          nix-collect-garbage -d (system + user)"
	@echo "  fmt            nixfmt every .nix file in the tree"
	@echo "  shellcheck     shellcheck every .sh file in the tree"
	@echo ""
	@echo "Variables (current values):"
	@echo "  HOST  = $(HOST)"
	@echo "  CACHE = $(CACHE)"
	@echo "  FLAKE = $(FLAKE)"

.PHONY: switch
switch:
	sudo nixos-rebuild switch --flake $(FLAKE)#$(HOST)

.PHONY: test
test:
	sudo nixos-rebuild test --flake $(FLAKE)#$(HOST)

.PHONY: build
build:
	nix build $(FLAKE)#nixosConfigurations.$(HOST).config.system.build.toplevel

.PHONY: update
update:
	nix flake update --flake $(FLAKE)

# Push the local host's closure to the cache. Requires `cachix` and
# `jq` on PATH and a configured authtoken (`cachix authtoken <token>`).
.PHONY: cache
cache:
	nix build $(FLAKE)#nixosConfigurations.$(HOST).config.system.build.toplevel --json \
	  | jq -r '.[].outputs | to_entries[].value' \
	  | cachix push $(CACHE)

.PHONY: check
check:
	nix flake check $(FLAKE)

.PHONY: clean
clean:
	sudo nix-collect-garbage -d
	nix-collect-garbage -d

# Format every .nix file. Requires nixfmt on PATH (in nixpkgs).
.PHONY: fmt
fmt:
	@find . -name '*.nix' -not -path './.git/*' -print0 \
	  | xargs -0 -r nixfmt

# Lint every .sh file. Requires shellcheck on PATH (in nixpkgs).
.PHONY: shellcheck
shellcheck:
	@find . -name '*.sh' -not -path './.git/*' -print0 \
	  | xargs -0 -r shellcheck
