Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,13 @@ package cmd

import (
"fmt"
"github.com/spf13/cobra"
"os"
"path/filepath"
"strings"

"github.com/spf13/cobra"
"stackroost/config"
"stackroost/internal"
"stackroost/internal/logger"
"strings"
)

var rootCmd = &cobra.Command{
Expand Down Expand Up @@ -128,6 +127,11 @@ var createDomainCmd = &cobra.Command{
os.Exit(1)
}

if err := internal.CreateMySQLUserAndDatabase(username, password); err != nil {
logger.Error(fmt.Sprintf("Database setup failed for %s: %v", username, err))
os.Exit(1)
}

logger.Success("Configuration file created")

filename := fmt.Sprintf("%s%s", domain, configGen.GetFileExtension())
Expand Down
22 changes: 22 additions & 0 deletions internal/database.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package internal

import (
"fmt"
"stackroost/internal/logger"
)
func CreateMySQLUserAndDatabase(username, password string) error {
logger.Info(fmt.Sprintf("Creating MySQL user and database for '%s'", username))

createUserCmd := fmt.Sprintf(`CREATE USER IF NOT EXISTS '%s'@'localhost' IDENTIFIED BY '%s';`, username, password)
createDBCmd := fmt.Sprintf(`CREATE DATABASE IF NOT EXISTS %s;`, username)
grantCmd := fmt.Sprintf(`GRANT ALL PRIVILEGES ON %s.* TO '%s'@'localhost';`, username, username)
flushCmd := `FLUSH PRIVILEGES;`
fullSQL := fmt.Sprintf("%s %s %s %s", createUserCmd, createDBCmd, grantCmd, flushCmd)
mysqlCmd := []string{"-e", fullSQL}
if err := RunCommand("sudo", append([]string{"mysql"}, mysqlCmd...)...); err != nil {
return fmt.Errorf("failed to create MySQL user or database: %v", err)
}

logger.Success(fmt.Sprintf("MySQL user and database '%s' created", username))
return nil
}