package main

import (
	"app-uploader/huawei"
	"app-uploader/utils"
	"fmt"
	"runtime"
	"strconv"
	"strings"
)

func main() {
	// 读取package.json版本数据
	// 复制app.json文件和logo文件
	// 读取配置
	appConf, err := utils.ReadAppConfig()
	if err != nil {
		fmt.Println("读取配置文件错误")
		return
	}
	uploadConf, err := utils.ReadConfig()
	if err != nil {
		fmt.Println("读取配置文件错误")
		return
	}
	dest := ""
	copyFiles := []string{}
	// 需要修改版本的文件
	modify := ""
	// 复制文件到对应目录
	switch appConf.Key {
	case "queenter":
		dest = uploadConf.Queenter.Dest
		copyFiles = uploadConf.Queenter.Files
		modify = uploadConf.Queenter.Modify
	default:
		return
	}
	// 复制文件到目标目录中
	for _, file := range copyFiles {
		err := utils.Copy(file, fmt.Sprintf("%s/%s", dest, file))
		if err != nil {
			fmt.Println(err)
			return
		}
	}
	// 获取版本信息
	version, err := utils.GetVersion()
	if err != nil {
		fmt.Println(err)
		return
	}
	appConf.Version = version
	appConfDest := fmt.Sprintf("%s/%s", dest, modify)
	err = utils.WriteAppConfig(appConf, appConfDest)
	if err != nil {
		fmt.Println(err)
		return
	}
	// 压缩文件
	// remoteswift-v1.0.0-x64-windows.zip
	zipFile := fmt.Sprintf("%s-v%s-%s-%s-test.zip", appConf.Key, version, runtime.GOARCH, runtime.GOOS)
	zipPath := fmt.Sprintf("output/%s", zipFile)
	fmt.Println("压缩文件中...")
	err = utils.Zip(zipPath, dest)
	if err != nil {
		fmt.Println("压缩文件出错")
		return
	}

	fmt.Println("上传中...")
	// 上传文件
	huawei.InitConfig()
	// http://spu3dv1.obs.cn-east-3.myhuaweicloud.com/pkg/lancher1.0.2.windows-amd64.zip
	obsDir := "pkg"
	obs, err := huawei.UploadFile(zipPath, obsDir, zipFile)

	if err != nil {
		fmt.Println(err)
		return
	}
	if len(obs.Url) < 1 {
		fmt.Println("上传zipfile错误")
		return
	}
	fmt.Println("succ uploaded=>", obs.Url)

	// 获取最新版本
	// 输出db文件
	outputDb := "output/db.json"
	sizeM, err := strconv.Atoi(strings.Replace(appConf.Size, "MB", "", -1))
	if err != nil {
		fmt.Println("转换size string->int 错误:", err)

	}

	err = utils.WriteVersionDb(&utils.Version{
		Name:    appConf.Key,
		Version: version,
		SizeM:   sizeM,
		Url:     fmt.Sprintf("https:%s", obs.Url),
	}, outputDb)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("上传成功")

}
