.PHONY: all init toolchain kernel uboot device-tree payload payload-built rootfs image flash clean config deps

# Default target
all: image

# Initialize build environment
init:
	cargo run -- init

# Build toolchain
toolchain:
	cargo run -- toolchain

# Build kernel
kernel:
	cargo run -- kernel

# Build U-Boot (optional)
uboot:
	cargo run -- uboot

# Build device tree
device-tree:
	cargo run -- device-tree

# Build hekate L4T boot files
payload:
	cargo run -- payload

# Build hekate L4T boot files with the locally built kernel
payload-built:
	cargo run -- payload --kernel built

# Create root filesystem
rootfs:
	cargo run -- rootfs

# Create bootable image (default: 8GB)
image:
	cargo run -- image --size $(or $(SIZE),8)

# Create image with desktop
desktop:
	cargo run -- image --size $(or $(SIZE),16) --desktop

# Flash to SD card
flash:
	@if [ -z "$(DEVICE)" ]; then \
		echo "Error: DEVICE not set. Usage: make flash DEVICE=/dev/sdX"; \
		exit 1; \
	fi
	cargo run -- flash $(DEVICE)

# Clean build artifacts
clean:
	cargo run -- clean

# Clean everything
clean-all:
	cargo run -- clean --all

# Show configuration
config:
	cargo run -- config

# Check dependencies
deps:
	@echo "Checking dependencies..."
	@which git > /dev/null 2>&1 || (echo "Missing: git" && exit 1)
	@which make > /dev/null 2>&1 || (echo "Missing: make" && exit 1)
	@which gcc > /dev/null 2>&1 || (echo "Missing: gcc" && exit 1)
	@which flex > /dev/null 2>&1 || (echo "Missing: flex" && exit 1)
	@which bison > /dev/null 2>&1 || (echo "Missing: bison" && exit 1)
	@which dtc > /dev/null 2>&1 || (echo "Missing: dtc" && exit 1)
	@which bc > /dev/null 2>&1 || (echo "Missing: bc" && exit 1)
	@which rsync > /dev/null 2>&1 || (echo "Missing: rsync" && exit 1)
	@echo "All dependencies found!"

# Help
help:
	@echo "ALARM Build System for Tegra X1 (ODNX02-A2)"
	@echo ""
	@echo "Usage:"
	@echo "  make init          Initialize build environment"
	@echo "  make toolchain     Install cross-compilation toolchain"
	@echo "  make kernel        Build Linux kernel"
	@echo "  make device-tree   Build device tree"
	@echo "  make payload       Build hekate payload"
	@echo "  make rootfs        Create root filesystem"
	@echo "  make image         Create bootable image (SIZE=16 for 16GB)"
	@echo "  make desktop       Create image with XFCE desktop"
	@echo "  make flash         Flash to SD card (DEVICE=/dev/sdX)"
	@echo "  make clean         Clean build artifacts"
	@echo "  make clean-all     Remove all build files"
	@echo "  make config        Show build configuration"
	@echo "  make deps          Check dependencies"
	@echo "  make help          Show this help"
