package main
import (
"encoding/json"
"fmt"
"net"
"os"
"os/exec"
"strconv"
"time"
)
func main() {
conn, err := net.Dial("tcp", "localhost:5050")
if err != nil {
fmt.Println("Error connecting:", err.Error())
os.Exit(1)
}
// Start a goroutine for receiving actions
go receiveActions(conn)
fmt.Println("Starting Uplink Bridge App")
}
// receiveAction reads and decodes JSON data from the connection
func receiveAction(conn net.Conn) map[string]interface{} {
buffer := make([]byte, 2048)
length, _ := conn.Read(buffer)
var data map[string]interface{}
json.Unmarshal(buffer[:length], &data)
return data
}
// sendData encodes the payload to JSON and sends it over the connection
func sendData(conn net.Conn, payload map[string]interface{}) {
send, _ := json.Marshal(payload)
conn.Write(append(send, '\n'))
}
// actionComplete constructs a JSON action_status response
func actionComplete(id interface{}) map[string]interface{} {
return map[string]interface{}{
"stream": "action_status",
"sequence": 0,
"timestamp": time.Now().UnixNano() / int64(time.Microsecond),
"action_id": id,
"state": "Completed",
"progress": 100,
"errors": []string{},
}
}
// reboot performs a system reboot
func reboot(action map[string]interface{}) {
payload := action["payload"].(map[string]interface{})
fmt.Println(payload)
resp := actionComplete(action["action_id"])
fmt.Println(resp)
sendData(conn, resp)
cmd := exec.Command("sudo", "reboot")
cmd.Run()
}
// receiveActions listens for actions and processes them
func receiveActions(conn net.Conn) {
for {
action := receiveAction(conn)
fmt.Println(action)
if action["name"] == "reboot" {
fmt.Println("reboot action received")
reboot(action)
}
}
}