package jattach

///*
//#cgo CFLAGS: -I include
//#cgo amd64 LDFLAGS: ${SRCDIR}/lib/libjattach_amd64.a
//#cgo arm64 LDFLAGS: ${SRCDIR}/lib/libjattach_arm64.a
//#include <stdlib.h>
//// declaration jattach
//int jattach(int pid, int argc, char** argv, int print_output);
//*/
//import "C"

import (
	"fmt"
	"github.com/coroot/coroot-node-agent/utils"
	"github.com/coroot/coroot-node-agent/utils/enums"
	klog "github.com/sirupsen/logrus"
	"os"
	"strings"
)

type JvmJattacher struct {
	Pid         uint32
	Args        []string
	PrintOutput int
}

func (j *JvmJattacher) JAttach() (int, error) {
	// cmd方式
	cwJattachCmdPath := utils.GetDefaultScriptsPath("cwjattach")
	// 执行升级
	args := []string{fmt.Sprintf("%d", j.Pid)}
	args = append(args, j.Args...)
	result, err := utils.AuthoritativeCMD(enums.RootUser, enums.DefaultTimeOut, os.Environ(), cwJattachCmdPath, args...)

	if err != nil {
		return -1, err
	}
	if strings.Contains(result, "JVM response code = 0") {
		return 0, nil
	} else {
		return -1, fmt.Errorf("JVM returned %s", result)
	}

	//
	//cArgs := make([]*C.char, len(j.Args))
	//for i, arg := range j.Args {
	//	cArgs[i] = C.CString(arg)
	//	defer C.free(unsafe.Pointer(cArgs[i])) // free mem
	//}
	//
	//// call C func jattach
	//// cArgs to **C.char
	//result := C.jattach(C.int(j.Pid), C.int(len(j.Args)), (**C.char)(unsafe.Pointer(&cArgs[0])), C.int(j.PrintOutput))
	//if int(result) != 0 {
	//	return int(result), fmt.Errorf("[JAttach] jattacher failed")
	//}
	//return int(result), nil
}

func (j *JvmJattacher) JDetach() (int, error) {
	// cmd方式
	cwJattachCmdPath := utils.GetDefaultScriptsPath("cwjattach")
	// 执行升级
	args := []string{fmt.Sprintf("%d", j.Pid)}
	args = append(args, j.Args...)
	result, err := utils.AuthoritativeCMD(enums.RootUser, enums.DefaultTimeOut, os.Environ(), cwJattachCmdPath, args...)

	if err != nil {
		klog.WithError(err).Errorf("Failed to detach JVM process")
		return -1, err
	}
	if strings.Contains(result, "JVM response code = 0") {
		return 0, nil
	} else {
		return -1, fmt.Errorf("JVM returned %s", result)
	}
}
