netmaker/serverctl/serverctl.go

81 lines
1.9 KiB
Go
Raw Normal View History

2021-04-07 00:33:01 +08:00
package serverctl
import (
"fmt"
"github.com/gravitl/netmaker/functions"
"io"
"net/http"
2021-04-07 00:33:01 +08:00
"os"
"os/exec"
)
func DownloadNetclient() error {
2021-04-07 00:33:01 +08:00
// Get the data
resp, err := http.Get("https://github.com/gravitl/netmaker/releases/download/latest/netclient")
if err != nil {
return err
}
defer resp.Body.Close()
2021-04-07 00:33:01 +08:00
// Create the file
out, err := os.Create("/etc/netclient/netclient")
if err != nil {
return err
}
defer out.Close()
2021-04-07 00:33:01 +08:00
// Write the body to file
_, err = io.Copy(out, resp.Body)
2021-04-07 00:33:01 +08:00
return err
}
func RemoveNetwork(network string) (bool, error) {
_, err := os.Stat("/etc/netclient/netclient")
if err != nil {
return false, err
}
cmdoutput, err := exec.Command("/etc/netclient/netclient","-c","remove","-n",network).Output()
if err != nil {
fmt.Println(string(cmdoutput))
return false, err
}
fmt.Println("Server removed from network " + network)
return true, err
2021-04-07 00:33:01 +08:00
}
2021-04-07 00:33:01 +08:00
func AddNetwork(network string) (bool, error) {
2021-04-07 00:33:01 +08:00
_, err := os.Stat("/etc/netclient")
if os.IsNotExist(err) {
os.Mkdir("/etc/netclient", 744)
} else if err != nil {
fmt.Println("couldnt find or create /etc/netclient")
return false, err
2021-04-07 00:33:01 +08:00
}
token, err := functions.CreateServerToken(network)
2021-04-07 00:33:01 +08:00
if err != nil {
return false, err
2021-04-07 00:33:01 +08:00
}
_, err = os.Stat("/etc/netclient/netclient")
if os.IsNotExist(err) {
err = DownloadNetclient()
if err != nil {
return false, err
}
2021-04-07 00:33:01 +08:00
}
err = os.Chmod("/etc/netclient/netclient", 0755)
if err != nil {
return false, err
}
cmdoutput, err := exec.Command("/etc/netclient/netclient","-c","install","-t",token,"-name","netmaker").Output()
2021-04-07 00:33:01 +08:00
if err != nil {
fmt.Println(string(cmdoutput))
return false, err
}
fmt.Println("Server added to network " + network)
return true, err
2021-04-07 00:33:01 +08:00
}