package cmd
import (
"fmt"
"github.com/spf13/cobra"
"go.bigb.es/cacher/internal/config"
)
var initCmd = &cobra.Command{
Use: "init",
Short: "Write ~/.config/cacher/config.toml and verify credentials",
Long: `Persist cacher's S3 connection settings to ~/.config/cacher/config.toml
so subsequent commands don't need flags or env vars. After writing, runs
the same smoke test as ` + "`cacher doctor`" + ` to fail fast on bad creds.
Auth files (--key-file, --secret-file) are recorded in the config but
not read here — they're read on demand by every subsequent command.
Credentials passed via CACHER_S3_KEY_ID / CACHER_S3_SECRET env vars
take precedence over the files at use time.`,
RunE: func(cmd *cobra.Command, args []string) error {
// Build the config we will persist. init does not honour the
// in-process config file — it always writes a fresh one.
cfg := config.Defaults()
if flagEndpoint != "" {
cfg.Endpoint = flagEndpoint
}
if flagRegion != "" {
cfg.Region = flagRegion
}
if flagBucket != "" {
cfg.Bucket = flagBucket
}
if flagPrefix != "" {
cfg.Prefix = flagPrefix
}
if flagKeyFile != "" {
cfg.KeyFile = flagKeyFile
}
if flagSecretFile != "" {
cfg.SecretFile = flagSecretFile
}
switch flagArchSuffix {
case "true":
cfg.ArchSuffix = true
case "false":
cfg.ArchSuffix = false
}
if err := cfg.Validate(); err != nil {
return err
}
path := flagConfigPath
if path == "" {
p, err := config.DefaultPath()
if err != nil {
return err
}
path = p
}
if err := config.Save(path, cfg); err != nil {
return err
}
fmt.Fprintf(cmd.OutOrStdout(), "wrote %s\n", path)
return runDoctor(cmd)
},
}
func init() {
addS3Flags(initCmd)
rootCmd.AddCommand(initCmd)
}