package main

import (
	"fmt"
	"net"
    // "os"
    "encoding/json"
    "github.com/aliyun/alibaba-cloud-sdk-go/services/slb"
    "github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"


   
)

const accessKeyId = "LTAIuPbTPL3LDDKN"
const accessSecret = "ORcNedKwWuwVtcq4IRFtUDZgS0b1le"



func GetOutBoundIP()(ip string, err error)  {
    addrs, err := net.InterfaceAddrs()
    if err != nil {
        fmt.Println(err)
    }
    for _, address := range addrs {

        // 检查ip地址判断是否回环地址
        if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
            if ipnet.IP.To4() != nil {
                ip = ipnet.IP.String()
            }

        }
    }
    return  ip, err

}

func GetInstancdFromSlb() (res [] string, err  error) {
    client, err := slb.NewClientWithAccessKey("cn-hangzhou", accessKeyId, accessSecret)
    request := slb.CreateDescribeLoadBalancersRequest()
    request.Scheme = "https"
    request.Tags = "[{\"tagKey\":\"app\",\"tagValue\":\"longvideoapi\"}]"
    response, err := client.DescribeLoadBalancers(request)

	if err != nil {
		fmt.Println(err.Error())       
        
	}
    loadBalancers := response.LoadBalancers.LoadBalancer
    for i := 0; i < len(loadBalancers); i++ {
        var loadBalancer = loadBalancers[i].LoadBalancerId
        res = append(res, loadBalancer)
    }
    // loadBalancer := responres  []string,se.DescribeLoadBalancersResponse
    // res = loadBalancer.String()
    return   res , err
}

func GetInastanceNameFromEcs(ipaddrs string)(name string , err error) {
    client, err := ecs.NewClientWithAccessKey("cn-hangzhou", accessKeyId, accessSecret)

    request := ecs.CreateDescribeInstancesRequest()
    request.Scheme = "https"
    fmt.Println("['" + ipaddrs + "'']")

    request.PrivateIpAddresses = "['" + ipaddrs + "']"

    response, err := client.DescribeInstances(request)
    if err != nil {
        fmt.Print(err.Error())
    }
    if  len(response.Instances.Instance) >0 {
        name= response.Instances.Instance[0].InstanceId

    } else {
        name = "Noname"
    }

    return name ,err 
}

func SetBackendServers(loadbalancer, backendServices string) (res string, err error) {


    client, err := slb.NewClientWithAccessKey("cn-hangzhou", accessKeyId, accessSecret)
    request := slb.CreateSetBackendServersRequest()
    request.Scheme = "https"

    request.LoadBalancerId = loadbalancer
    request.BackendServers = backendServices
    response, err := client.SetBackendServers(request)


    if err != nil {
        fmt.Print(err.Error())
    }
    fmt.Printf("response is %#v\n", response)

    return

}

func  main(){
	ipaddr, err := GetOutBoundIP()
    if err != nil {
        fmt.Println(err)
    }

    LoadbalancersIDs, err:= GetInstancdFromSlb()
    InstanceID , err := GetInastanceNameFromEcs(ipaddr)

    backendServices := make(map[string]string)
    backendServices["ServerId"] = InstanceID
    backendServices["Weight"] = "100"
    backend_json, _ := json.Marshal(backendServices)
    backend_string := "[" + string(backend_json) + "]"

    fmt.Printf(backend_string)

    if len(LoadbalancersIDs) >0 {

        for _, LoadbalancersID := range LoadbalancersIDs {
            _, err = SetBackendServers(LoadbalancersID, backend_string)

            if err != nil {
            fmt.Print(err.Error())
            }


        }
    }









    // fmt.Println(response)


}
