82 lines
1.8 KiB
Go
82 lines
1.8 KiB
Go
|
package cmd
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"io"
|
||
|
"log"
|
||
|
"os"
|
||
|
"os/user"
|
||
|
"strings"
|
||
|
|
||
|
"github.com/spf13/cobra"
|
||
|
)
|
||
|
|
||
|
var (
|
||
|
configDirectory string = strings.Join([]string{getHomeDir(), ".muldap"}, "/")
|
||
|
configFile string = "config.toml"
|
||
|
configFilePath string = strings.Join([]string{configDirectory, configFile}, "/")
|
||
|
defaultPerms os.FileMode = 0700
|
||
|
)
|
||
|
|
||
|
func init() {
|
||
|
rootCmd.AddCommand(setupCmd)
|
||
|
}
|
||
|
|
||
|
var setupCmd = &cobra.Command{
|
||
|
Use: "setup",
|
||
|
Short: "Set up your user environment for muldap",
|
||
|
Long: "An easy way to get your environment up and running using muldap",
|
||
|
Run: func(cmd *cobra.Command, args []string) {
|
||
|
// check if the configuration directory exists
|
||
|
if _, err := os.Stat(configDirectory); os.IsNotExist(err) {
|
||
|
fmt.Printf("Creating new configuration directory at %s\n", configDirectory)
|
||
|
_ = os.Mkdir(configDirectory, defaultPerms)
|
||
|
}
|
||
|
|
||
|
// check if the configuration file exists
|
||
|
if _, err := os.Stat(configFilePath); os.IsNotExist(err) {
|
||
|
fmt.Printf("Creating new configuration file at %s\n", configFilePath)
|
||
|
_, err = os.Create(configFilePath)
|
||
|
if err != nil {
|
||
|
log.Fatal(err)
|
||
|
}
|
||
|
|
||
|
// write the configuration to the new file
|
||
|
copyFile("./config.toml", configFilePath)
|
||
|
} else {
|
||
|
// notify the user the file already exists
|
||
|
fmt.Printf("Your configuration file already exists at %s\n", configFilePath)
|
||
|
}
|
||
|
},
|
||
|
}
|
||
|
|
||
|
// get user's home directory
|
||
|
func getHomeDir() string {
|
||
|
usr, err := user.Current()
|
||
|
if err != nil {
|
||
|
log.Fatal(err)
|
||
|
}
|
||
|
|
||
|
return usr.HomeDir
|
||
|
}
|
||
|
|
||
|
// copy a file
|
||
|
func copyFile(src, dst string) {
|
||
|
in, err := os.OpenFile(src, os.O_RDONLY, os.ModeAppend)
|
||
|
if err != nil {
|
||
|
log.Fatal(err)
|
||
|
}
|
||
|
defer in.Close()
|
||
|
|
||
|
out, err := os.OpenFile(dst, os.O_WRONLY, os.ModeAppend)
|
||
|
if err != nil {
|
||
|
log.Fatal(err)
|
||
|
}
|
||
|
defer out.Close()
|
||
|
|
||
|
_, err = io.Copy(out, in)
|
||
|
if err != nil {
|
||
|
log.Fatal(err)
|
||
|
}
|
||
|
}
|