# Makefile 离线构建扩展
# 将此内容追加到主 Makefile 或单独使用
# 使用方法: make -f Makefile.offline <target>

# 离线构建配置
CACHE_DIR ?= ./build-cache
VERSION ?= latest

# ========== 离线构建目标 ==========

.PHONY: offline-export
offline-export:
	@echo "导出离线构建缓存..."
	@bash scripts/offline/export-cache.sh $(CACHE_DIR)

.PHONY: offline-build
offline-build:
	@echo "使用缓存进行离线构建..."
	@bash scripts/offline/build-offline.sh $(CACHE_DIR) $(VERSION)

.PHONY: offline-setup
offline-setup:
	@echo "解压并设置离线缓存..."
	@if [ ! -d "$(CACHE_DIR)" ]; then \
		echo "查找缓存压缩包..."; \
		cache_file=$$(ls -t build-cache-*.tar.gz 2>/dev/null | head -1); \
		if [ -z "$$cache_file" ]; then \
			echo "错误: 未找到缓存压缩包 (build-cache-*.tar.gz)"; \
			exit 1; \
		fi; \
		echo "解压 $$cache_file..."; \
		tar -xzf "$$cache_file"; \
	fi
	@echo "✓ 离线缓存准备完成"

# 单个服务的离线构建
.PHONY: %-offline-build
%-offline-build:
	@echo "离线构建 $*..."
	@$(eval CACHE_FILE := $(CACHE_DIR)/buildkit/$*-cache)
	@$(eval IMAGE_NAME := $(if $(filter deer-flow%,$*),$*,datamate-$*))
	@if [ ! -d "$(CACHE_FILE)" ]; then \
		echo "错误: $* 的缓存不存在于 $(CACHE_FILE)"; \
		exit 1; \
	fi
	@docker buildx build \
		--cache-from type=local,src=$(CACHE_FILE) \
		--network=none \
		-f scripts/images/$*/Dockerfile \
		-t $(IMAGE_NAME):$(VERSION) \
		--load \
		. || echo "警告: $* 离线构建失败"

# 兼容原 Makefile 的构建目标（离线模式）
.PHONY: build-offline
build-offline: offline-setup
	@$(MAKE) offline-build

.PHONY: help-offline
help-offline:
	@echo "离线构建命令:"
	@echo "  make offline-export              - 在有网环境导出构建缓存"
	@echo "  make offline-setup               - 解压并准备离线缓存"
	@echo "  make offline-build               - 在无网环境使用缓存构建"
	@echo "  make <service>-offline-build     - 离线构建单个服务"
	@echo ""
	@echo "示例:"
	@echo "  # 有网环境导出缓存"
	@echo "  make offline-export"
	@echo ""
	@echo "  # 传输 build-cache-*.tar.gz 到无网环境"
	@echo "  scp build-cache-20250202.tar.gz user@offline-server:/path/"
	@echo ""
	@echo "  # 无网环境构建"
	@echo "  make offline-setup"
	@echo "  make offline-build"
