package common

import (
	"fmt"
	"io/ioutil"
	"log"
	"net"
	"os/exec"
	"strconv"
	"strings"
	"time"

	l4g "github.com/alecthomas/log4go"

	"github.com/mitchellh/go-homedir"
	"golang.org/x/crypto/ssh"
)

type SubnetsResponse struct {
	Subnets []Subnet `json:"Subnets"`
}

type Subnet struct {
	AvailabilityZoneId string `json:"AvailabilityZoneId"`
	SubnetId           string `json:"SubnetId"`
}

func ConnectInstance(ec2Host, cerPath, loginUser, cmd string) (string, bool) {
	sshPort := 22

	config := &ssh.ClientConfig{
		Timeout: 300 * time.Second,
		User:    loginUser,
		Auth:    []ssh.AuthMethod{publicKeyAuthFunc(cerPath)},
		HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
			// use OpenSSH's known_hosts file if you care about host validation
			return nil
		},
	}

	l4g.Info("command input: %s", cmd)

	//dial 获取ssh client
	addr := fmt.Sprintf("%s:%d", ec2Host, sshPort)
	sshClient, err := ssh.Dial("tcp", addr, config)
	if err != nil {
		l4g.Error("创建ssh client 失败:%s", err)
		return "创建ssh client 失败", false
	}
	defer sshClient.Close()

	//创建ssh-session
	session, err := sshClient.NewSession()
	if err != nil {
		l4g.Error("创建ssh session 失败:%s", err)
		return "创建ssh session 失败", false
	}
	defer session.Close()
	//执行远程命令
	combo, err := session.CombinedOutput(cmd)
	if err != nil {
		l4g.Error("远程执行cmd失败:%s, 命令输出：%s", err, string(combo))
		return fmt.Sprintf("远程执行cmd 失败, 命令输出:%s", string(combo)), false
	}
	l4g.Info("命令输出:%s", string(combo))
	return string(combo), true
}

func publicKeyAuthFunc(kPath string) ssh.AuthMethod {
	keyPath, err := homedir.Expand(kPath)
	if err != nil {
		log.Fatal("find key's home dir failed", err)
	}
	key, err := ioutil.ReadFile(keyPath)
	if err != nil {
		log.Fatal("ssh key file read failed", err)
	}
	// Create the Signer for this private key.
	signer, err := ssh.ParsePrivateKey(key)
	if err != nil {
		log.Fatal("ssh key signer failed", err)
	}
	return ssh.PublicKeys(signer)
}

func StartEC2Instance(ec2Host, cerPath, loginUser, instanceId, iamUser string) {
	cmd := fmt.Sprintf("aws ec2 start-instances --instance-ids %s", instanceId)
	l4g.Info("start EC2 cmd is %s", cmd)

	for round := 0; round < 10; round++ {
		l4g.Info("host: %s, cerPath: %s, loginUser: %s,  hostCmd: %s", ec2Host, cerPath, loginUser, cmd)
		err, getEC2InstanceStatusResult := ConnectInstance(ec2Host, cerPath, loginUser, cmd)
		l4g.Error("StartEC2Instance error is %s", err)
		if getEC2InstanceStatusResult == true {
			break
		}
		time.Sleep(time.Second * 60)
	}
}

func StopEC2Instance(ec2Host, cerPath, loginUser, instanceId, iamUser string) {
	cmd := fmt.Sprintf("aws ec2 stop-instances --instance-ids %s", instanceId)
	l4g.Info("stop EC2 cmd is %s", cmd)
	ConnectInstance(ec2Host, cerPath, loginUser, cmd)
}

func GetEC2InstanceStatus(ec2Host, cerPath, loginUser, instanceId, iamUser string) bool {
	cmd := fmt.Sprintf("aws ec2 describe-instance-status --instance-ids %s", instanceId)
	l4g.Info("GetEC2InstanceStatus cmd is %s", cmd)
	for round := 0; round < 15; round++ {
		l4g.Info("host: %s, cerPath: %s, loginUser: %s,  hostCmd: %s", ec2Host, cerPath, loginUser, cmd)
		err, getEC2InstanceStatusResult := ConnectInstance(ec2Host, cerPath, loginUser, cmd)
		l4g.Error("getEC2InstanceStatusResult error is %s", err)
		if getEC2InstanceStatusResult == true && strings.Contains(err, "running") {
			return true
		}
		time.Sleep(time.Second * 60)
	}
	return false
}

func RunKafka(ec2Host, cerPath, loginUser string) {
	//cmd := "nohup /home/ec2-user/kafka_2.11-0.10.2.1/bin/kafka-server-start.sh /home/ec2-user/kafka_2.11-0.10.2.1/config/server.properties &"
	cmd := "sudo sh ./run_kafka.sh"
	l4g.Info("RunKafka kafka cmd is %s", cmd)
	for round := 0; round < 3; round++ {
		err, getEC2InstanceStatusResult := ConnectInstance(ec2Host, cerPath, loginUser, cmd)
		l4g.Error("RunKafka kafka error is %s", err)
		if getEC2InstanceStatusResult == true {
			break
		}
		time.Sleep(time.Second * 60)
	}
}

func PutAwsBucketPolicy(accountId, externalId, ec2Host, cerPath, loginUser, iamUser string) {
	//替换policy.json
	cpcmd := fmt.Sprintf("cp -f /home/ec2-user/policy.json /home/ec2-user/policy1.json")
	ConnectInstance(ec2Host, cerPath, loginUser, cpcmd)

	sedcmd := fmt.Sprintf("sed -i 's/AccountID/%s/g' /home/ec2-user/policy1.json", accountId)
	ConnectInstance(ec2Host, cerPath, loginUser, sedcmd)

	sedcmd = fmt.Sprintf("sed -i 's/ExternalIdData/%s/g' /home/ec2-user/policy1.json", externalId)
	ConnectInstance(ec2Host, cerPath, loginUser, sedcmd)

	s3cmd := fmt.Sprintf("aws iam create-role --role-name %s --assume-role-policy-document file:///home/ec2-user/policy1.json", externalId)
	l4g.Info("s3cmd is : %s", s3cmd)
	ConnectInstance(ec2Host, cerPath, loginUser, s3cmd)

	s3cmd = fmt.Sprintf("aws iam attach-role-policy --role-name %s --policy-arn arn:aws:iam::aws:policy/AmazonS3FullAccess", externalId)
	l4g.Info("s3cmd is : %s", s3cmd)
	ConnectInstance(ec2Host, cerPath, loginUser, s3cmd)

}

func Chmod600(fileAddress string) {
	cmd := fmt.Sprintf("chmod 600 %s", fileAddress)
	chmodCmd := exec.Command("/bin/bash", "-c", cmd)

	l4g.Info("cmd is :%s", chmodCmd)
	_, err := chmodCmd.Output()
	if err != nil {
		l4g.Error("do Chmod600 err:%s, sedcmd is:%s", err, cmd)
		return
	}

}

func DeleteStrip(data []string) []string {
	var newData []string
	for _, value := range data {
		if len(value) != 0 {
			l4g.Info("value:%s", value)
			newData = append(newData, value)
		}

	}
	return newData

}

func GetProvider(ec2Host, cerPath, loginUser, projectId, region, env string) string {
	var cmd string
	if strings.Contains(env, "dev") {
		cmd = fmt.Sprintf("KUBECONFIG=./infra-api-kubeconfig-dev.yaml kubectl get network -n nightly-ms-%s | grep %s", projectId, region)
	} else {
		cmd = fmt.Sprintf("KUBECONFIG=./infra-api-kubeconfig.yaml kubectl get network -n staging-%s | grep %s", projectId, region)
	}

	l4g.Info("get instance by lable, cmd is:%s", cmd)
	data, _ := ConnectInstance(ec2Host, cerPath, loginUser, cmd)
	dataList := strings.Split(data, " ")
	newData := DeleteStrip(dataList)
	for _, value := range newData {
		if value == "aws-free-tier" || value == "aws" || value == "eks" || value == "gke" || value == "gcp" {
			return value
		}
	}
	l4g.Info("data is:%s", newData)
	return ""
}

func DeleteAwsBucket(bucketname, ec2Host, cerPath, loginUser string) error {
	s3cmd := fmt.Sprintf("aws s3 rb %s --force", bucketname)
	l4g.Info("awscmd is : %s", s3cmd)
	output, flag := ConnectInstance(ec2Host, cerPath, loginUser, s3cmd)
	if flag != true {
		return l4g.Error(output)
	}
	return nil
}

func CreateAwsBucket(bucketname, ec2Host, cerPath, loginUser string) error {
	s3cmd := fmt.Sprintf("aws s3 mb %s", bucketname)
	l4g.Info("awscmd is : %s", s3cmd)
	output, flag := ConnectInstance(ec2Host, cerPath, loginUser, s3cmd)
	if flag != true {
		return l4g.Error(output)
	}
	return nil
}

func GetAwsBucketSize(bucketname, ec2Host, cerPath, loginUser string) (float64, error) {
	bucketList := strings.Split(bucketname, "/")
	s3cmd := fmt.Sprintf("aws s3api list-objects --bucket %s --query \"sum(Contents[].Size)\"", bucketList[2])
	l4g.Info("awscmd is : %s", s3cmd)
	data, result := ConnectInstance(ec2Host, cerPath, loginUser, s3cmd)
	if result == false {
		return 0, l4g.Error(data)
	}
	dataList := strings.Split(data, "\n")
	size, err := strconv.ParseFloat(dataList[0], 64)
	l4g.Info("dataList:%v, size:%f", dataList, size)
	if err != nil {
		l4g.Error("strconv.ParseFloat failed:%s", err)
		return 0, l4g.Error("strconv.ParseFloat failed:%s", err)
	}
	return size, nil
}
