.PHONY: init install link unlink rebuild update purge edit hw help

NIXOS_DIR := /etc/nixos
REPO_DIR := $(shell pwd)
SETTINGS := settings.nix

# Colors for output
GREEN := \033[0;32m
YELLOW := \033[0;33m
RED := \033[0;31m
NC := \033[0m # No Color

help:
	@echo "NixOS Config"
	@echo ""
	@echo "  make init     - first time setup"
	@echo "  make hw       - generate hardware-configuration.nix"
	@echo "  make rebuild  - rebuild nixos"
	@echo "  make update   - upgrade + rebuild"
	@echo "  make purge    - garbage collect"
	@echo "  make link     - symlink to /etc/nixos"
	@echo "  make unlink   - remove symlink"
	@echo "  make edit     - edit settings.nix"

init:
	@$(MAKE) --no-print-directory hw
	@$(MAKE) --no-print-directory link
	@echo ""
	@echo "done. run 'make rebuild' when ready"

link:
	@if [ -L "$(NIXOS_DIR)" ]; then \
		sudo rm $(NIXOS_DIR); \
	elif [ -d "$(NIXOS_DIR)" ]; then \
		sudo mv $(NIXOS_DIR) $(NIXOS_DIR).bak; \
		echo "backed up /etc/nixos to /etc/nixos.bak"; \
	fi
	@sudo ln -sf $(REPO_DIR) $(NIXOS_DIR)
	@echo "linked $(REPO_DIR) -> $(NIXOS_DIR)"

unlink:
	@if [ -L "$(NIXOS_DIR)" ]; then \
		sudo rm $(NIXOS_DIR); \
		sudo mkdir -p $(NIXOS_DIR); \
		echo "unlinked"; \
	else \
		echo "/etc/nixos is not a symlink"; \
	fi

rebuild:
	sudo nixos-rebuild switch

update:
	sudo nixos-rebuild switch --upgrade

purge:
	sudo nix-collect-garbage -d
	sudo /run/current-system/bin/switch-to-configuration boot

check:
	nix-instantiate '<nixpkgs/nixos>' -A system --dry-run

hw:
	sudo nixos-generate-config --show-hardware-config > hardware-configuration.nix

edit:
	@$${EDITOR:-nano} $(SETTINGS)
