package cluster

import (
	"bytes"
	"fmt"
	"log"
	"net"

	"golang.org/x/crypto/ssh"
)

func ssHConnect(user, password, host string, port int) (*ssh.Session, error) {
	var (
		auth         []ssh.AuthMethod
		addr         string
		clientConfig *ssh.ClientConfig
		client       *ssh.Client
		session      *ssh.Session
		err          error
	)
	// get auth method
	auth = make([]ssh.AuthMethod, 0)
	auth = append(auth, ssh.Password(password))
	hostKeyCallbk := func(hostname string, remote net.Addr, key ssh.PublicKey) error {
		return nil
	}
	clientConfig = &ssh.ClientConfig{
		User: user,
		Auth: auth,
		// Timeout:             30 * time.Second,
		HostKeyCallback: hostKeyCallbk,
	}
	// connet to ssh
	addr = fmt.Sprintf("%s:%d", host, port)

	if client, err = ssh.Dial("tcp", addr, clientConfig); err != nil {
		return nil, err
	}
	// create session
	if session, err = client.NewSession(); err != nil {
		return nil, err
	}
	return session, nil
}

//wget https://www.jianyu360.com/upload/extract_v3.tgz
var sshstr = `
#!/bin/bash
cd /opt
kill -9 $(pidof extract_v3)
rm -rf extract_v3*
wget http://10.170.187.34:8300/upload/extract_v3.tgz
tar -xzvf extract_v3.tgz
cd /opt/extract_v3
chmod 777 extract_v3
nohup ./extract_v3 >/dev/null 2>&1 &
exit
`

func RunSsh(ip, password string, port int) {
	var stdOut, stdErr bytes.Buffer
	session, err := ssHConnect("root", password, ip, port)
	if err != nil {
		log.Fatal(err)
	}
	defer session.Close()
	session.Stdout = &stdOut
	session.Stderr = &stdErr

	//session.Run("wget https://www.jianyu360.com/upload/2017/04/22/201704221113374530.jpg")
	session.Run(sshstr)
	log.Println("ok")
}
