package main

import (
	"bufio"
	"flag"
	"fmt"
	"os"
	"strings"
	"wdd.io/agent-common/utils"
)

var LocalKubeConfigFile = "/root/.kube/config"

// build for offline usage
// C:\Users\wdd\go\bin\gox.exe -osarch="linux/amd64" -output "build/agent-operator_{{.OS}}_{{.Arch}}"
// C:\Users\wdd\go\bin\gox.exe -osarch="linux/amd64 linux/arm64" -output "build/agent-operator_{{.OS}}_{{.Arch}}"

// C:\Users\wddsh\go\bin\gox.exe -osarch="linux/amd64" -output "build/agent-operator_{{.OS}}_{{.Arch}}"

func BuildDefaultK8sOperator() {

	// build from local LocalKubeConfigFile
	if !utils.FileExists(LocalKubeConfigFile) {
		log.ErrorF("%s not exits! error!", LocalKubeConfigFile)
		return
	}

	readFile, err := os.ReadFile(LocalKubeConfigFile)
	if err != nil {
		log.ErrorF("error reading %s, error %s", LocalKubeConfigFile, err.Error())
		return
	}

	op := CmiiK8sOperator{}
	op.BuildCurrentClientFromConfig(readFile)
	DefaultCmiiOperator = op
}

func RealProjectRunner() {

	// ops

	// update
	//result := UpdateCmiiImageTagFromNameTagList(realNamespace, bgtg.AllCmiiImageTagList)
	//result := UpdateCmiiImageTagFromNameTagMap(realNamespace, xmyd.Real540ImageTagMap)
	//utils.BeautifulPrint(result)

	//for _, imageFullName := range xmyd.AllCmiiImageTagList {
	//	appName := image.ImageFullNameToAppName(imageFullName)
	//	if appName == "" {
	//		log.InfoF("can't update %s", imageFullName)
	//		continue
	//	}
	//	exists := op.DeploymentExist(realNamespace, appName)
	//	if exists == nil {
	//		log.InfoF("app of  %s not eixts", appName)
	//		continue
	//	}
	//
	//	_ = op.DeploymentUpdateTag(realNamespace, appName, image.ImageFullNameToImageTag(imageFullName))
	//
	//}

	// backup system app tag
	//backendMap, frontendMap, srsMap := BackupAllCmiiDeploymentToMap(realNamespace)
	//utils.BeautifulPrint(backendMap)
	//utils.BeautifulPrint(frontendMap)
	//utils.BeautifulPrint(srsMap)

	// scale deployment
	//ScaleCmiiFrontendDeploymentToDesiredReplicas(realNamespace, 1)
	//ScaleCmiiBackendDeploymentToDesiredReplicas(realNamespace, 1)

	// update from map
}

func CmiiRunner() {

}

var DLTUHelp = `
DLTUHelp
  dltu [ossUrlPrefix] [ossFileName] [localGzipFolderOrGzipFile] [harborHostFullName] [namespace]
`

func main() {

	// C:\Users\wddsh\go\bin\gox.exe -osarch="linux/amd64" -output "build/operator_{{.OS}}_{{.Arch}}"

	//RealProjectRunner()
	//var mode string
	//flag.StringVar(&mode, "mode", "mode", "agent run mode")
	//flag.Parse()
	//
	//BuildDefaultK8sOperator()
	//
	//BackupAllDeploymentFromEnvToFile(mode)

	//解析命令行参数
	var mode string
	flag.StringVar(&mode, "mode", "mode", "agent run mode")
	flag.Parse()

	if mode == "image" {

		BuildDefaultK8sOperator()
		// 堡垒机模式 的 镜像美容
		// 初始化堡垒机模式
		for {

			reader := bufio.NewReader(os.Stdin)
			for {
				fmt.Printf(DLTUHelp)
				fmt.Print("enter ==> ")

				text, _ := reader.ReadString('\n')
				split := strings.Split(text, " ")
				var result []string
				for _, s := range split {
					text = strings.TrimSpace(s)
					if text == "" {
						continue
					}

					result = append(result, text)
				}

				if len(result) != 6 {
					fmt.Println("input error!")
					fmt.Printf(DLTUHelp)
					return
				}

				ossUrlPrefix := result[1]
				ossFileName := result[2]
				localGzipFolderOrGzipFile := result[3]
				harborHostFullName := result[4]
				namespace := result[5]

				fmt.Println("ossUrlPrefix: ", ossUrlPrefix)
				fmt.Println("ossFileName: ", ossFileName)
				fmt.Println("localGzipFolderOrGzipFile: ", localGzipFolderOrGzipFile)
				fmt.Println("harborHostFullName: ", harborHostFullName)
				fmt.Println("namespace: ", namespace)
				fmt.Println()

				downloadFromOss := true
				if ossFileName == "0" {
					downloadFromOss = false
				}

				// DLTU
				targetImageFullNameList := A_DownloadLoadTagUpload(downloadFromOss, ossUrlPrefix, ossFileName, localGzipFolderOrGzipFile, harborHostFullName)

				// 是否需要更新
				if namespace != "" {
					for _, targetImageFullName := range targetImageFullNameList {
						if !DefaultCmiiOperator.DeploymentUpdateTagByImageFullName(namespace, targetImageFullName) {
							fmt.Printf("[Update] update [%s] [%s] failed", namespace, targetImageFullName)
						}
					}
				}

				fmt.Println()
			}
		}
	} else if mode == "operator" {

	}

}
