package utils

import (
	"archive/zip"
	"errors"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"runtime"
	"strings"
	"updater/huawei"
)

// 上传当前exe文件
func UploadExe() (string, error) {
	// 获取当前执行程序
	// G:\wk\lancher-svc\src\lancher.exe
	appExePath, _ := os.Executable()
	// G:/wk/lancher-svc/src/lancher.exe
	appExePath = strings.Replace(appExePath, "\\", "/", -1)
	// G:/wk/lancher-svc/src/
	appExeDir, _ := filepath.Split(appExePath)
	fmt.Println(appExeDir)

	// 压缩当前执行程序
	// 压缩单个文件

	zipFile := fmt.Sprintf("%s%s.%s-%s.zip", "updater", Version, runtime.GOOS, runtime.GOARCH)
	zipPath := fmt.Sprintf("%s%s", appExeDir, zipFile)
	err := ZipFile(zipPath, appExePath)
	if err != nil {
		return "", err
	}
	// 获取操作系统和版本号确定上传文件名
	obsDir := "pkg"
	//上传压缩后的文件到obs
	// http://spu3dv1.obs.cn-east-3.myhuaweicloud.com/pkg/updater1.0.2.windows-amd64.zip
	huawei.InitConfig()
	obs, err := huawei.UploadFile(zipPath, obsDir, zipFile)
	if err != nil {
		return "", err
	}
	if len(obs.Url) < 1 {
		fmt.Println("上传zipfile错误")
		return "", errors.New("上传zipfile错误")
	}
	fmt.Println("succ uploaded=>", obs.Url)

	return zipPath, nil

}

func ZipFile(zipPath string, exePath string) error {
	os.RemoveAll(zipPath)
	archive, err := os.Create(zipPath)
	if err != nil {
		return err
	}
	defer archive.Close()
	zipWriter := zip.NewWriter(archive)

	f, err := os.Open(exePath)
	if err != nil {
		return err
	}
	defer f.Close()
	_, exeFile := filepath.Split(exePath)

	w, err := zipWriter.Create(exeFile)
	if err != nil {
		return err
	}
	if _, err := io.Copy(w, f); err != nil {
		return err
	}

	zipWriter.Close()
	return nil
}
