package controller

/*
#cgo CFLAGS: -fvisibility=hidden
#cgo LDFLAGS:-lpthread -ldl -lstdc++ -lrt -lm -lc -lz -luv -lcjson -luvdbus -lcurl -lcrypto -ldbus-1 -lsqlite3 -ls2json -lquickmail -luuid -lcutils -lconfig
#include <stdio.h>
#include <stdlib.h>
#include <uvdbus/skins.h>
#include <uvdbus/libuv_dbus.h>
#include <uvdbus/log.h>
*/
import "C"
import (
	"encoding/json"
	"netease_control_center/interfaces/http"
	"netease_control_center/interfaces/log"
	"netease_control_center/utils"
	"os"
	"os/exec"
	"unsafe"
)

func CopyLogfiles() {
	log.Println(log.DebugLog, "Begin to Copy log flies to sdcard!")

	if data, err := exec.Command("/bin/sh", "-c", "/usr/sbin/backuplocalfiles.sh backup").CombinedOutput(); err == nil {
		log.Println(log.DebugLog, "CopyLogfiles: ", " result:", string(data))
	} else {
		log.Println(log.DebugLog, "CopyLogfiles", " error!", err, string(data))
	}

	log.Println(log.DebugLog, "Finish Copy log flies to sdcard!")
}

func UploadLog(tp int64, feedbackId int64) {
	var tmp struct {
		FeedbackId int64             `json:"feedbackId"`
		Type       int64             `json:"type"`
		VboxInfo   *http.HttpReqbase `json:"vboxInfo"`
	}

	tmp.FeedbackId = feedbackId
	tmp.Type = tp
	tmp.VboxInfo = &http.Reqbase

	if data, err := json.Marshal(tmp); err == nil {
		log.Println(log.DebugLog, "Get result:", string(data))
		CUpgradeLog(string(data))
	} else {
		log.Println(log.ErrorLog, "Decode data err!", err)
	}
}

func CUpgradeLog(arg string) {
	cpath := C.CString(arg)
	if unsafe.Pointer(cpath) != unsafe.Pointer(uintptr(0)) {
		log.Println(log.DebugLog, "Tell hx upload files!")
		C.HttpPostLogFile((*C.char)(unsafe.Pointer(cpath)))
		C.free(unsafe.Pointer(cpath))
	} else {
		log.Println(log.ErrorLog, "Get cpath err!")
	}
}

func SilentBootFileCheck() (isSilent bool) {
	path := "/tmp/ccsilentboot"
	defer func() {
		if isSilent == false {
			if f, _ := os.Create(path); f != nil {
				f.Close()
			}
		}
	}()

	return utils.PathExist(path)
}
