package main

import (
	"fmt"
	"log"
	"strings"

	pub "git.zhiweidata.top/taotengfei/AD-Control-Golang/public"
)

func checkWindows() bool {
	var status bool
	out := pub.Execcmd_output(`cscript C:\Windows\SysWOW64\slmgr.vbs /xpr  //nologo`)
	outs := strings.TrimSpace(string(out))
	winProductName, _ := query_key_one(`SOFTWARE\Microsoft\Windows NT\CurrentVersion\SoftwareProtectionPlatform`, "BackupProductKeyDefault")

	if strings.Contains(outs, "计算机已永久激活") {
		log.Printf("当前已永久激活,使用的密钥为%s", winProductName)
		return false
	} else if strings.Contains(outs, "找不到产品密钥") {
		status = true
	} else if strings.Contains(outs, "处于通知模式") {
		status = true
	} else if strings.Contains(outs, "批量激活将于") {
		log.Printf("当前已激活Windows")
		return false
	} else {
		fmt.Println(outs)
	}

	log.Printf("准备激活Windows")

	return status
}
func requestWindowsKey() (string, string, error) {
	product, err := query_key_one(`SOFTWARE\Microsoft\Windows NT\CurrentVersion`, "ProductName")
	if err != nil {
		return "", "", err
	}
	if product == "" {
		return "", "", fmt.Errorf("无法查询到系统产品名称")
	}
	log.Printf("系统产品名称:%s\n", product)
	// 从服务器获取密钥
	pub.SendBoomServer(pub.Msg_Boom_Active, product)
	if pub.MS.Error {
		return "", "", fmt.Errorf(pub.MS.Errmsg)
	}
	return product, pub.MS.S, nil
}
func activeWindows() error {
	if !checkWindows() {
		return nil
	}
	product, key, err := requestWindowsKey()
	if err != nil {
		return err
	}
	log.Printf("请求到%s的密钥:%s\n", product, key)
	// kmsfile := "vlmcsd-Windows-x64.exe"
	// kms := fmt.Sprintf(`%s\%s`, pub.Dir_tmp, kmsfile)
	// if pub.NotExist(kms) {
	// 	log.Printf("下载kms服务器")

	// 	url := fmt.Sprintf("%s/%s", pub.Msg_File, kmsfile)
	// 	if err := pub.DownloadFileInside(url, kms); err != nil {
	// 		log.Printf("下载失败")
	// 		return err
	// 	}
	// }

	if !pub.Telnet("192.168.0.21", "1688") {
		return fmt.Errorf("无法连接到知微kms")
	}
	log.Printf("探测到kms服务器已经运行")

	outstr := string(pub.Execcmd_output(`cscript C:\Windows\SysWOW64\slmgr.vbs /skms 192.168.0.21:1688 //nologo`))

	if strings.Contains(outstr, "拒绝访问: 所请求的操作需要提升特权") {
		return fmt.Errorf("请使用管理员权限打开本程序")
	} else if strings.Contains(outstr, "密钥管理服务计算机名称成功地设置为") {
		log.Printf("kms设置成功")
	}

	outstr = string(pub.Execcmd_output(`cscript C:\Windows\SysWOW64\slmgr.vbs /ipk ` + key + " //nologo"))
	if strings.Contains(outstr, "拒绝访问: 所请求的操作需要提升特权") {
		return fmt.Errorf("请使用管理员权限打开本程序")
	} else if strings.Contains(outstr, "成功地安装了产品密钥") {
		log.Printf("成功安装产品密钥")
	}

	outstr = string(pub.Execcmd_output(`cscript C:\Windows\SysWOW64\slmgr.vbs /ato  //nologo`))
	if strings.Contains(outstr, "拒绝访问: 所请求的操作需要提升特权") {
		return fmt.Errorf("请使用管理员权限打开本程序")
	} else if strings.Contains(outstr, "0x8007000D 数据无效") {
		return fmt.Errorf("kms地址无法是本地地址")
	} else if strings.Contains(outstr, "成功地激活了产品") {
		log.Printf("激活%s成功", product)
	}
	// log.Println(outstr)
	return nil
}
