package script

import (
	"encoding/json"
	"gitee.ltd/lxh/logger/log"
	"github.com/spf13/cast"
	"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
	"os"
	"wireguard-dashboard/client"
	"wireguard-dashboard/component"
	"wireguard-dashboard/constant"
	"wireguard-dashboard/model/entity"
	"wireguard-dashboard/model/template_data"
	"wireguard-dashboard/repository"
	"wireguard-dashboard/utils"
)

type Script struct{}

func NewScript() Script {
	return Script{}
}

func (s Script) Do() error {
	if err := s.DBMigrate(); err != nil {
		return err
	}

	if err := s.CreateSuperAdmin(); err != nil {
		return err
	}

	if err := s.InitServer(); err != nil {
		log.Error(err.Error())
	}

	return nil
}

// DBMigrate
// @description: 实体migrate
// @receiver s
// @return error
func (s Script) DBMigrate() error {
	var ent = []any{
		new(entity.User),
		new(entity.Server),
		new(entity.Client),
		new(entity.Setting),
	}

	return client.DB.AutoMigrate(ent...)
}

// CreateSuperAdmin
// @description: 创建首个超级管理员
// @receiver s
// @return error
func (s Script) CreateSuperAdmin() error {
	var count int64
	if err := client.DB.Model(&entity.User{}).Where("is_admin = ?", 1).Count(&count).Error; err != nil {
		return err
	}

	// 没有超管就创建一个
	if count > 0 {
		return nil
	}

	// 生成一下头像
	avatarPath, err := utils.Avatar().GenerateAvatar()
	if err != nil {
		log.Errorf("生成头像失败: %v", err.Error())
		return err
	}

	if err = repository.User().Save(&entity.User{
		Avatar:   avatarPath,
		Name:     "超牛管理员",
		Account:  "admin",
		Email:    "",
		Password: "admin123",
		IsAdmin:  constant.SuperAdmin,
		Status:   constant.Normal,
	}); err != nil {
		return err
	}

	return nil
}

// InitServer
// @description: 初始化服务端信息
// @receiver s
// @return error
func (s Script) InitServer() error {
	var count int64
	if err := client.DB.Model(&entity.Server{}).Count(&count).Error; err != nil {
		return err
	}

	if count > 0 {
		return nil
	}

	// 初始化服务端的全局配置
	var data = map[string]any{
		"endpointAddress":     utils.Network().GetHostPublicIP(),
		"dnsServer":           []string{"10.10.10.1/24"},
		"MTU":                 1450,
		"persistentKeepalive": 15,
		"firewallMark":        "0xca6c",
		"table":               "",
		"configFilePath":      "/etc/wireguard/wg0.conf",
	}
	dataJ, _ := json.Marshal(data)

	globalSet := &entity.Setting{
		Code:     "SERVER_SETTING",
		Data:     string(dataJ),
		Describe: "服务端全局配置",
	}
	if err := repository.System().Save(globalSet); err != nil {
		return err
	}

	// 生成密钥
	privateKey, err := wgtypes.GeneratePrivateKey()
	if err != nil {
		log.Errorf("生成密钥失败: %v", err.Error())
		return err
	}

	// 根据密钥生成公钥
	publicKey := privateKey.PublicKey()
	serverEnt := &entity.Server{
		IpScope:        "10.10.10.1/24",
		ListenPort:     51820,
		PrivateKey:     privateKey.String(),
		PublicKey:      publicKey.String(),
		PostUpScript:   "",
		PreDownScript:  "",
		PostDownScript: "",
	}

	// 没有服务端，开始初始化
	if err := repository.Server().Save(serverEnt); err != nil {
		return err
	}

	// 处理一下要渲染到配置文件上的数据
	serverConfig := template_data.Server{
		Address:    serverEnt.IpScope,
		ListenPort: serverEnt.ListenPort,
		PrivateKey: serverEnt.PrivateKey,
		MTU:        cast.ToInt(data["MTU"]),
		PostUp:     serverEnt.PostUpScript,
		PreDown:    serverEnt.PreDownScript,
		PostDown:   serverEnt.PostDownScript,
		Table:      cast.ToString(data["table"]),
	}

	execData := map[string]any{
		"Server": serverConfig,
	}

	var templatePath, outFilePath string
	if os.Getenv("GIN_MODE") != "release" {
		templatePath = "E:\\Workspace\\Go\\wireguard-dashboard\\template\\wg.conf"
		outFilePath = "E:\\Workspace\\Go\\wireguard-dashboard\\wg0.conf"
	} else {
		templatePath = "./template/wg.conf"
		outFilePath = cast.ToString(data["configFilePath"])
	}

	// 数据库保存完毕，应用配置到配置文件当中
	err = component.Wireguard().Apply(templatePath, outFilePath, execData)
	if err != nil {
		log.Errorf("应用配置文件失败: %v", err.Error())
		return err
	}

	return nil
}
