package app

import (
	"time"
	"chain33-pai/pkg/setting"
	"bytes"
	"os/exec"
	"fmt"
	"chain33-pai/service/pai_service"
)

var RollChan chan bool

func RollbackJob() {
	for {
		if value,ok := <- RollChan; ok {
			if !value {
				continue
			}
			err := rollback()
			if err == nil {
				tlog.Info("rollback success","err",nil)
			} else {
				tlog.Error("rollback fail ","err",err)
			}
		}
		time.Sleep(time.Second * 1)
	}
}


func rollback() error {
	BityuanFlag = true
	_,err := SafeCloseNode()
	if err != nil {
		BityuanFlag  = false
		return err
	}
	var pai pai_service.Pai
	err = pai.SetPai()
	if err != nil {
		tlog.Error("SetPai","err",err)
		BityuanFlag  = false
		return err
	}
	if pai.LocalLastHeight == 0 {
		tlog.Error("LocalLastHeight","height",pai.LocalLastHeight)
		BityuanFlag  = false
		return err
	}
	rollheight := pai.LocalLastHeight - 1000
	if (pai.LocalLastHeight - 1000) <= 0 {
		rollheight = 1
	}
	time.Sleep(time.Second * 2)
	tlog.Info("rollback start","height",pai.LocalLastHeight,"rollbackheight",rollheight)
	var buf bytes.Buffer
	path := GetAbsPath(setting.BityuanSetting.Name)
	if path == "" {
		tlog.Error("GetAbsPath","err","path not exists")
		BityuanFlag  = false
		return err
	}
	cmd := exec.Command(path+"/"+setting.BityuanSetting.Name, "-rollback",fmt.Sprintf("%d",rollheight))
	cmd.Stdout = &buf
	err = cmd.Run()
	if err != nil {
		BityuanFlag  = false
		return err
	}
	tlog.Info("rollback end","height",pai.LocalLastHeight,"rollbackheight",rollheight)
	BityuanFlag  = false
	return nil
}