package main

import (
	"fmt"
	"github.com/mitchellh/go-homedir"
	"io/ioutil"
	"net"
	"time"

	l4g "github.com/alecthomas/log4go"
	"golang.org/x/crypto/ssh"
)

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
		},
	}

	//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 {
		l4g.Error("find key's home dir failed", err)
	}
	key, err := ioutil.ReadFile(keyPath)
	if err != nil {
		l4g.Error("ssh key file read failed", err)
	}
	// Create the Signer for this private key.
	signer, err := ssh.ParsePrivateKey(key)
	if err != nil {
		l4g.Error("ssh key signer failed", err)
	}
	return ssh.PublicKeys(signer)
}

func main(){
	ec2Host := "ec2-35-80-101-93.us-west-2.compute.amazonaws.com"
	cerPath := "./instancesshkey/test2.pem"
	loginUser := "ec2-user"
	cmd := "sh run_kafka.sh"
	for round := 0; round < 3; round++ {
		l4g.Info("host: %s, cerPath: %s, loginUser: %s,  hostCmd: %s", ec2Host, cerPath, loginUser, cmd)
		err, runkafkaResult := ConnectInstance(ec2Host, cerPath, loginUser, cmd)
		l4g.Error("addRoute error is %s", err)
		if runkafkaResult == true {
			break
		}
		time.Sleep(time.Second * 5)
	}
}

