STOW_TARGET := $(HOME)

.PHONY: check-stow
check-stow:
	@command -v stow >/dev/null 2>&1 && { \
		echo "✅ stow already installed"; \
		exit 0; \
	}; \
	OS="$$(uname -s)"; \
	@echo "📦 stow not found. Detected OS: $$OS"; \
	case "$$OS" in \
		Linux) \
			if [ -f /etc/arch-release ]; then \
				echo "-> Installing via pacman"; \
				sudo pacman -S --needed stow; \
			elif [ -f /etc/debian_version ]; then \
				echo "-> Installing via apt"; \
				sudo apt update && sudo apt install -y stow; \
			else \
				echo "❌ Unsupported Linux distro"; \
				exit 1; \
			fi \
			;; \
		Darwin) \
			@echo "-> Installing via Homebrew"; \
			@command -v brew >/dev/null 2>&1 || { \
				echo "❌ Homebrew not installed"; \
				exit 1; \
			}; \
			@brew install stow \
			;; \
		*) \
			@echo "❌ Unsupported OS: $$OS"; \
			exit 1; \
			;; \
	esac

.PHONY: pull-updates
pull-updates:
	@echo "Pulling all recent updates"
	@git pull origin main
	@git submodule update --recursive --remote

.PHONY: link
link: check-stow
	@echo "Linking dotfiles to machine"
	@for pkg in *; do \
		[ -d "$$pkg" ] || continue; \
		echo "📦 stowing $$pkg"; \
		stow -R "$$pkg" -t "$(STOW_TARGET)" --adopt; \
	done
