gomonop/main.go
Emmanuel BENOîT 5432360f0e
refactor(pkg): refactor Plugin to make it easier to test
Writing the plugin's output string and exiting the program will no
longer take place in the plugin status itself. It will only be done in
the main program.
2024-07-19 23:46:33 +02:00

73 lines
1.4 KiB
Go

package main
import (
"fmt"
"os"
"path/filepath"
"nocternity.net/gomonop/cmd/sslcert"
"nocternity.net/gomonop/cmd/zoneserial"
"nocternity.net/gomonop/pkg/plugin"
"nocternity.net/gomonop/pkg/program"
"nocternity.net/gomonop/pkg/version"
)
var (
programs map[string]program.Builder = map[string]program.Builder{
"check_ssl_certificate": sslcert.NewProgram,
"check_zone_serial": zoneserial.NewProgram,
}
)
func getProgram() program.Program {
ownName := filepath.Base(os.Args[0])
if builder, ok := programs[ownName]; ok {
return builder()
}
if len(os.Args) < 2 {
fmt.Printf("Syntax: %s <program> [arguments]\n", ownName)
fmt.Printf(" %s --programs|-p\n", ownName)
fmt.Printf(" %s --version|-v", ownName)
}
switch os.Args[1] {
case "--programs", "-p":
for name := range programs {
fmt.Println(name)
}
os.Exit(0)
case "--version", "-v":
fmt.Printf("%s %s\n", ownName, version.Version())
os.Exit(0)
}
if builder, ok := programs[os.Args[1]]; ok {
os.Args = os.Args[1:]
return builder()
}
fmt.Printf("Unknown program: %s\n", os.Args[1])
os.Exit(1)
return nil
}
func main() {
program := getProgram()
output := program.Output()
defer func() {
if r := recover(); r != nil {
output.SetState(plugin.StatusUnknown, "Internal error")
output.AddLinef("Error info: %v", r)
}
fmt.Println(output.String())
os.Exit(output.ExitCode())
}()
if program.CheckArguments() {
program.RunCheck()
}
}