go_clientinfo/cmd/clientinfo/main.go
2024-12-12 02:22:54 -05:00

119 lines
2.7 KiB
Go

package main
import (
`errors`
`fmt`
`log`
`os`
`github.com/creasty/defaults`
`github.com/davecgh/go-spew/spew`
`github.com/jessevdk/go-flags`
`r00t2.io/clientinfo/args`
`r00t2.io/clientinfo/server`
`r00t2.io/clientinfo/version`
`r00t2.io/goutils/logging`
`r00t2.io/sysutils/envs`
)
func main() {
var err error
var logger *logging.MultiLogger
var logFlagsRuntime int = logFlags
var srv *server.Server
var args *args.Args = new(args.Args)
var flagsErr *flags.Error = new(flags.Error)
var parser *flags.Parser = flags.NewParser(args, flags.Default)
if _, err = parser.Parse(); err != nil {
switch {
case errors.As(err, &flagsErr):
switch {
// These print their relevant messages by themselves.
case errors.Is(
flagsErr.Type,
flags.ErrHelp,
),
errors.Is(
flagsErr.Type,
flags.ErrCommandRequired,
),
errors.Is(
flagsErr.Type,
flags.ErrRequired,
):
return
default:
log.Panicln(err)
}
default:
log.Panicln(err)
}
}
if version.Ver, err = version.Version(); err != nil {
log.Panicln(err)
}
// If args.Version or args.DetailVersion are true, just print them and exit.
if args.DetailVersion || args.Version {
if args.Version {
fmt.Println(version.Ver.Short())
return
} else if args.DetailVersion {
fmt.Println(version.Ver.Detail())
return
}
}
// We want to set up logging before anything else.
if args.DoDebug {
logFlagsRuntime = logFlagsDebug
}
logger = logging.GetMultiLogger(args.DoDebug, "ClientInfo")
if err = logger.AddDefaultLogger(
"default",
logFlagsRuntime,
"/var/log/clientinfo/clientinfo.log", "~/logs/clientinfo.log",
); err != nil {
log.Panicln(err)
}
if err = logger.Setup(); err != nil {
log.Panicln(err)
}
logger.Info("main: ClientInfo version %v", version.Ver.Short())
logger.Debug("main: ClientInfo version (extended):\n%v", version.Ver.Detail())
defer logger.Shutdown()
// TODO: WORKAROUND: https://github.com/jessevdk/go-flags/issues/408
if envs.HasEnv("CINFO_URI") {
args.Listen.Listen = os.Getenv("CINFO_URI")
}
if err = defaults.Set(args); err != nil {
logger.Err("main: Failed to set CLI arg defaults: %v", err)
log.Panicln(err)
}
logger.Debug("main: Initialized with args:\n%v", spew.Sdump(args))
if err = validate.Struct(args); err != nil {
logger.Err("main: Received error when validating args: %v", err)
log.Panicln(err)
}
if srv, err = server.NewServer(logger, args); err != nil {
logger.Err("main: Received error when creating server: %v", err)
log.Panicln(err)
}
logger.Debug("main: Starting server.")
if err = srv.Run(); err != nil {
logger.Err("main: Received error when running server: %v", err)
log.Panicln(err)
}
defer srv.Close()
logger.Debug("main: Exiting.")
}