package cmd

import (
	"os"
	"path/filepath"

	"gitea.loveuer.com/yizhisec/pkg3/logger"
	"github.com/spf13/cobra"
	"yizhisec.com/hsv2/forge/internal/opt"
	"yizhisec.com/hsv2/forge/pkg/resource"
)

func makeFlannel() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "flannel",
		Short: "Build Flannel resources",
		Long:  `Build and prepare Flannel network resources.`,
		RunE: func(cmd *cobra.Command, args []string) error {
			var (
				err      error
				location = filepath.Join(opt.Cfg.Make.Dir, "dependency", "flannel")
			)

			logger.Info("MakeFlannel: 开始构建 flannel 资源...")

			logger.Debug("MakeFlannel location: %s", location)
			if err = os.Mkdir(location, 0755); err != nil {
				logger.Error("MakeFlannel: 创建目录 %s 失败", location)
				logger.Debug("MakeFlannel: 创建目录 %s 失败: %v", location, err)
				return err
			}

			if err = os.WriteFile(filepath.Join(location, "flannel.yaml"), resource.YAMLFlannel, 0644); err != nil {
				logger.Error("MakeFlannel: 创建文件 %s 失败", filepath.Join(location, "flannel.yaml"))
				logger.Debug("MakeFlannel: 创建文件 %s 失败: %v", filepath.Join(location, "flannel.yaml"), err)
				return err
			}

			logger.Info("MakeFlannel: 构建 flannel 成功!!!")

			return nil
		},
	}

	return cmd
}
