.PHONY: test lint check build clean help

# ── Paths ──────────────────────────────────────────────────────────────
REPO_ROOT      := $(abspath $(dir $(lastword $(MAKEFILE_LIST))))
PROFILE_DIR    := $(REPO_ROOT)/packaging/archiso
SCRIPTS_DIR    := $(REPO_ROOT)/packaging/scripts
TESTS_DIR      := $(REPO_ROOT)/tests

# Shell scripts to lint with shellcheck
SHELL_SCRIPTS  := \
	$(PROFILE_DIR)/profiledef.sh \
	$(PROFILE_DIR)/build.sh \
	$(PROFILE_DIR)/airootfs/usr/local/bin/samios \
	$(PROFILE_DIR)/airootfs/usr/local/bin/choose-mirror \
	$(PROFILE_DIR)/airootfs/root/.automated_script.sh \
	$(SCRIPTS_DIR)/samios-desktop-setup.sh \
	$(TESTS_DIR)/test_helper.sh \
	$(TESTS_DIR)/test_profiledef.sh \
	$(TESTS_DIR)/test_packages.sh \
	$(TESTS_DIR)/test_pacman_conf.sh \
	$(TESTS_DIR)/test_samios_cli.sh \
	$(TESTS_DIR)/test_font_policy.sh \
	$(TESTS_DIR)/run_tests.sh

SHELLCHECK     ?= shellcheck
SHELLCHECK_OPTS := --severity=warning
# SC2034 (unused var) is expected in profile definitions and CLI stubs
SHELLCHECK_EXCLUDE := --exclude=SC2034

# ── Targets ────────────────────────────────────────────────────────────

help: ## Show this help
	@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | \
		awk 'BEGIN {FS = ":.*?## "}; {printf "  \033[36m%-12s\033[0m %s\n", $$1, $$2}'

test: ## Run the test suite
	@echo "Running SamiOS test suite..."
	@bash $(TESTS_DIR)/run_tests.sh --verbose

lint: ## Run shellcheck on all shell scripts
	@echo "Running shellcheck..."
	@for script in $(SHELL_SCRIPTS); do \
		if [ -f "$$script" ]; then \
			echo "  shellcheck $$script"; \
			$(SHELLCHECK) $(SHELLCHECK_OPTS) $(SHELLCHECK_EXCLUDE) "$$script" || exit 1; \
		fi \
	done
	@echo "shellcheck passed ✓"

check: lint test ## Run lint + test (CI entry point)

build: ## Build the SamiOS ISO (requires archiso + root)
	@echo "Building SamiOS ISO..."
	@cd $(PROFILE_DIR) && sudo ./build.sh

clean: ## Remove build artifacts
	@echo "Cleaning build artifacts..."
	@rm -rf /tmp/samios-build
	@rm -rf $(PROFILE_DIR)/out
	@echo "Clean complete"
