mctl/cmd/login.go
jake 658adfbe16 delete added, more details below
- readme updates
- delete command added
- commands now saved in a map vs fields
- login and run now ensure config has been run to prevent errors
2025-04-17 17:24:09 -04:00

71 lines
1.6 KiB
Go

/*
Copyright © 2025 Jake jake.young.dev@gmail.com
*/
package cmd
import (
"bufio"
"errors"
"fmt"
"os"
"code.jakeyoungdev.com/jake/mctl/client"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
// loginCmd represents the login command
var loginCmd = &cobra.Command{
Use: "login",
Example: "mctl login",
SilenceUsage: true,
Short: "Login to server and send commands",
Long: `Login to server using saved config and enter command loop
sending commands to server and printing the response.`,
Run: func(cmd *cobra.Command, args []string) {
//grab saved credentials
server := viper.Get("server").(string)
cli, err := client.New()
cobra.CheckErr(err)
defer cli.Close()
//start command loop
fmt.Println("Connected! Type 'mctl' to close")
scanner := bufio.NewScanner(os.Stdin)
var runningCmd string
for runningCmd != "mctl" {
fmt.Printf("RCON@%s /> ", server)
if scanner.Scan() {
runningCmd = scanner.Text()
if runningCmd == "" {
continue
}
//mctl exits command terminal
if runningCmd == "mctl" {
break
}
res, err := cli.Command(runningCmd)
cobra.CheckErr(err)
fmt.Printf("\n%s\n", res)
}
}
fmt.Printf("Disconnected from %s\n", server)
},
PreRunE: func(cmd *cobra.Command, args []string) error {
//ensure config command has been run
if viper.Get("server") == "" || viper.Get("password") == "" || viper.Get("port") == 0 {
return errors.New("the 'config' command must be run before you can interact with servers")
}
return nil
},
}
func init() {
rootCmd.AddCommand(loginCmd)
}