package cli import ( "encoding/json" "fmt" "os" "path/filepath" "github.com/DataDrake/cli-ng/v2/cmd" "github.com/hyprspace/hyprspace/schema" "github.com/multiformats/go-multibase" ) // InitFlags Contains flags for the init command. type InitFlags struct { Name string `long:"name" desc:"Name to include in the suggested peer entry."` } // Init creates a configuration for a Hyprspace Interface. var Init = cmd.Sub{ Name: "init", Alias: "i", Short: "Initialize An Interface Config", Flags: &InitFlags{}, Run: InitRun, } // InitRun handles the execution of the init command. func InitRun(r *cmd.Root, c *cmd.Sub) { ifName := r.Flags.(*GlobalFlags).InterfaceName if ifName == "" { ifName = "hyprspace" } configPath := r.Flags.(*GlobalFlags).Config if configPath == "" { configPath = "/etc/hyprspace/" + ifName + ".json" } keyBytes, peerId, err := GenerateKeyPair() checkErr(err) // Setup an initial default config. new := schema.Config{ PrivateKey: multibase.MustNewEncoder(multibase.Base58BTC).Encode(keyBytes), ListenAddresses: []string{ "/ip4/0.0.0.0/tcp/8001", "/ip4/0.0.0.0/udp/8001/quic-v1", "/ip6/::/tcp/8001", "/ip6/::/udp/8001/quic-v1", }, } out, err := json.MarshalIndent(&new, "", " ") checkErr(err) err = os.MkdirAll(filepath.Dir(configPath), os.ModePerm) checkErr(err) f, err := os.Create(configPath) checkErr(err) _, err = f.Write(out) checkErr(err) err = f.Close() checkErr(err) fmt.Printf("Initialized new config at %s\n", configPath) fmt.Println("Add this entry to your other peers:") fmt.Println("{") name := c.Flags.(*InitFlags).Name if name == "" { hostname, err := os.Hostname() if err == nil { name = hostname } } if name != "" { fmt.Printf(" \"name\": \"%s\",\n", name) } fmt.Printf(" \"id\": \"%s\"\n", peerId) fmt.Println("}") }