// nolint: gochecknoinits, gochecknoglobals, exhaustivestruct, goerr113 package cmd import ( "fmt" "os" "github.com/rs/zerolog/log" "github.com/spf13/cobra" "github.com/spf13/viper" "go.xsfx.dev/samurai/internal/config" "go.xsfx.dev/samurai/internal/server" ) var ( version = "dev" commit = "none" date = "unknown" ) var ( keyPath string cfgFile string ) var rootCmd = &cobra.Command{ Use: "samurai", Run: func(cmd *cobra.Command, args []string) { if err := cmd.Help(); err != nil { log.Fatal().Msg(err.Error()) } os.Exit(1) }, } var runCmd = &cobra.Command{ Use: "run", Short: "Run SSH server", PreRunE: initConfig, Run: func(cmd *cobra.Command, args []string) { server.Run(keyPath) }, } var versionCmd = &cobra.Command{ Use: "version", Short: "Print version", Run: func(cmd *cobra.Command, args []string) { fmt.Printf("samurai %s, commit %s, %s", version, commit, date) // nolint: forbidigo }, } var addUserCmd = &cobra.Command{ Use: "add-user", Short: "Add user", PreRunE: initConfig, RunE: func(cmd *cobra.Command, args []string) error { if err := config.AddUser(); err != nil { return fmt.Errorf("could not add user: %w", err) } return nil }, } func init() { // Version command. rootCmd.AddCommand(versionCmd) rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "", "config file") // Run command. rootCmd.AddCommand(runCmd) runCmd.Flags().StringVarP(&keyPath, "private-key", "k", "", "path of private SSH key") if err := viper.BindPFlag("private-key", runCmd.Flags().Lookup("private-key")); err != nil { log.Fatal().Msg(err.Error()) } if err := runCmd.MarkFlagRequired("private-key"); err != nil { log.Fatal().Msg(err.Error()) } // Add-User command. rootCmd.AddCommand(addUserCmd) } func initConfig(cmd *cobra.Command, args []string) error { if cfgFile != "" { viper.SetConfigFile(cfgFile) if err := viper.ReadInConfig(); err != nil { log.Fatal().Msg(err.Error()) } } else { return fmt.Errorf("needs config file") } viper.SetEnvPrefix("SAMURAI") viper.AutomaticEnv() return nil } func Execute() { if err := rootCmd.Execute(); err != nil { log.Fatal().Msg(err.Error()) } }