/* Copyright © 2023 NAME HERE */ package cmd import ( "bytes" "encoding/json" "fmt" "git.jmbit.de/jmb/patchman/client/utils" "git.jmbit.de/jmb/patchman/common" "github.com/google/uuid" "github.com/spf13/viper" "io" "log" "net/http" "os" "github.com/spf13/cobra" ) var token string var output string var serverUrl string type Registration struct { hostname string token string secret string } type ApiResponse struct { uuid uuid.UUID } // registerCmd represents the register command var registerCmd = &cobra.Command{ Use: "register", Short: "Register with server", Long: `Register an endpoint with a patchman server: patchman register --output /path/to/config --server https://patchman.example.com:443 --token `, Run: func(cmd *cobra.Command, args []string) { secret, err := common.RandomString(64) if err != nil { fmt.Fprintln(os.Stderr, "could not generate secret, please provide it manually!") secret = "CHANGEME" } fmt.Println("registering with Patchman Server") viper.SetDefault("server", serverUrl) viper.SetDefault("secret", secret) viper.SetConfigName("client.yaml") viper.SetConfigType("yaml") registration := Registration{ hostname: utils.GetHostname(), token: token, secret: secret, } jsondata, err := json.Marshal(registration) utils.HandleErrorFatal(err, "Could not parse registration Data") request, err := http.NewRequest("POST", fmt.Sprintf("%s/v0/endpoint/register", serverUrl), bytes.NewBuffer(jsondata)) utils.HandleErrorFatal(err, "Could not generate registration request") request.Header.Set("Content-Type", "application/json") client := &http.Client{} response, err := client.Do(request) utils.HandleErrorFatal(err, "Error making registration request") defer func(Body io.ReadCloser) { err := Body.Close() if err != nil { utils.HandleError(err, "Could not close reader") } }(response.Body) if response.StatusCode != http.StatusCreated { log.Printf("Request failed with response %s", response.Status) } }, } func init() { rootCmd.AddCommand(registerCmd) // Here you will define your flags and configuration settings. // Cobra supports Persistent Flags which will work for this command // and all subcommands, e.g.: // registerCmd.PersistentFlags().String("foo", "", "A help for foo") // Cobra supports local flags which will only run when this command // is called directly, e.g.: // registerCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") registerCmd.Flags().StringVar(&output, "output", "/etc/patchman/client.yaml", "Config file to create") registerCmd.Flags().String("server", "", "URL to Patchman server") registerCmd.Flags().String("token", "", "Registration token from Patchman Server") }