BackGo/cmd/interfacecli.go

72 lines
1.9 KiB
Go

package cmd
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"git.pixelridgesoftworks.com/BackGo/pkg/backup"
)
type InterfaceCLI struct {
NodeAddress string
DBManager *backup.DBManager
}
func NewInterfaceCLI(nodeAddress string, dbManager *backup.DBManager) *InterfaceCLI {
if dbManager == nil {
panic("DBManager cannot be nil")
}
return &InterfaceCLI{
NodeAddress: nodeAddress,
DBManager: dbManager,
}
}
func (cli *InterfaceCLI) TriggerCommand(action, value string) error {
return cli.sendCommandToNode("trigger", value)
}
func (cli *InterfaceCLI) GetInfo(value string) error {
return cli.sendCommandToNode("get_info", value)
}
func (cli *InterfaceCLI) AddNode(hostname, token string) error {
expectedIP := "" // Implement IP determination logic here
if !cli.DBManager.VerifyHostname(hostname, expectedIP) {
return fmt.Errorf("hostname %s does not resolve to the expected IP %s", hostname, expectedIP)
}
if err := cli.DBManager.CreateToken(hostname, token); err != nil {
return fmt.Errorf("failed to create token for hostname %s: %v", hostname, err)
}
fmt.Printf("Node %s added successfully with token %s\n", hostname, token)
return nil
}
func (cli *InterfaceCLI) GenCert(nodeName string) error {
return cli.sendCommandToNode("gencert", nodeName)
}
func (cli *InterfaceCLI) sendCommandToNode(action, value string) error {
payload := backup.CommandPayload{
Action: action,
Node: cli.NodeAddress,
Value: value,
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("error marshaling command payload: %v", err)
}
resp, err := http.Post(fmt.Sprintf("http://%s/api/command", cli.NodeAddress), "application/json", bytes.NewReader(payloadBytes))
if err != nil {
return fmt.Errorf("error sending command to node %s: %v", cli.NodeAddress, err)
}
defer resp.Body.Close()
fmt.Printf("Command '%s' sent to node %s successfully\n", action, cli.NodeAddress)
return nil
}