work/config.go

70 lines
1.9 KiB
Go

package main
import (
"fmt"
"log"
"os"
"path/filepath"
"github.com/spf13/viper"
)
type Config struct {
SSHUser string `mapstructure:"SSH_USER"`
SSHHost string `mapstructure:"SSH_HOST"`
JumpUser string `mapstructure:"JUMP_USER"`
JumpHost string `mapstructure:"JUMP_HOST"`
WorkstationHost string `mapstructure:"WORKSTATION_HOST"`
WorkstationUser string `mapstructure:"WORKSTATION_USER"`
WorkstationMac string `mapstructure:"WORKSTATION_MAC"`
RDPUser string `mapstructure:"RDP_USER"`
RDPPassword string `mapstructure:"RDP_PASSWORD"`
WorkstationIP string `mapstructure:"WORKSTATION_IP"`
SSHPort int `mapstructure:"SSH_PORT"`
// DatabasePath string `mapstructure:"DATABASE_PATH"`
}
type Flags struct {
ShowWeek bool
ShowMonth bool
ShowExport bool
ExportName string
}
func loadConfig() (Config, error) {
var cfg Config
configPath, err := os.UserConfigDir()
if err != nil {
return cfg, fmt.Errorf("could not get user config dir: %w", err)
}
workConfigPath := filepath.Join(configPath, "work")
configFile := filepath.Join(workConfigPath, "config.toml")
if err := os.MkdirAll(workConfigPath, 0750); err != nil {
return cfg, fmt.Errorf("could not create config directory '%s': %w", workConfigPath, err)
}
viper.SetConfigFile(configFile)
viper.SetConfigType("toml")
viper.AutomaticEnv()
if err := viper.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
return cfg, fmt.Errorf("error reading config file '%s': %w", configFile, err)
}
log.Printf("INFO: Config file '%s' not found, using defaults/env vars.", configFile)
}
if err := viper.UnmarshalKey("default", &cfg); err != nil {
if err := viper.Unmarshal(&cfg); err != nil {
return cfg, fmt.Errorf("error decoding config from '%s': %w", configFile, err)
}
}
if cfg.SSHPort == 0 {
cfg.SSHPort = 22
}
return cfg, nil
}