watch-spring/cmd/watch_linux.go

113 lines
2.8 KiB
Go

//go:build linux
// +build linux
package cmd
import (
"context"
"fmt"
"log"
"os"
"os/signal"
"syscall"
"time"
"gitea.urkob.com/mcr-swiss/watch-spring/internal"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
var Watch = &cobra.Command{
Use: "watch",
Short: "",
Long: ``,
Run: func(cmd *cobra.Command, args []string) {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute*5) // or any appropriate time
defer cancel()
// log.SetFlags(log.Ldate | log.Lmicroseconds)
// log.SetFlags(log.Lmicroseconds)
// if cfg.LogFile {
// logFileName := fmt.Sprintf("%s.txt", time.Now().Format(strings.ReplaceAll(time.RFC1123Z, ":", "_")))
// f, err := os.OpenFile(logFileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o644)
// if err != nil {
// panic(err)
// }
// defer f.Close()
// log.SetOutput(f)
// }
dirToWatch, err := cmd.Flags().GetString("dir")
if err != nil {
panic(fmt.Errorf("dir %w", err))
}
logLevel, err := cmd.Flags().GetUint("log-level")
if err != nil {
panic(fmt.Errorf("bucket %w", err))
}
logger := logrus.New()
logger.SetLevel(logrus.Level(logLevel))
logger.Info("start check")
defer logger.Info("end check")
// C:\scripts\watch-spring.exe --dir "C:\backup\ovh5win2oneshot" --script="C:\scripts\rclone-deploy.bat"
notif := internal.NewNotifier()
w, err := internal.NewWatcher(logger, notif, internal.Execute)
if err != nil {
panic(err)
}
defer func() {
if err := w.Close(); err != nil {
log.Fatalf("watcherIface.Close: %s\n", err)
}
}()
if err := w.Monitor(dirToWatch); err != nil {
log.Fatalf("watcherIface.Monitor: %s\n", err)
}
errChan := make(chan error)
go w.Listen(ctx, errChan, "", "")
// Handle termination on ctrl+signalChan
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, os.Interrupt, syscall.SIGTERM)
for {
select {
case <-signalChan:
log.Println("shutdown")
os.Exit(1)
case err, ok := <-errChan:
if !ok {
panic(fmt.Errorf("channel has been closed"))
}
if err != nil {
log.Printf("watcherIface.Monitor: %s\n", err)
continue
}
}
}
// if err := mailSrv.SendOK(email.EmailWithAttachments{
// To: cfg.MailTo,
// Bucket: bucketName,
// BackupDir: dirToWatch,
// Count: map[string]int{
// "count_ok": countOK,
// "count_local": countLocal,
// "count_b2": countB2,
// "count_not_in_local": countNotInLocal,
// "count_not_in_cloud": countNotInCloud,
// },
// Attachments: []email.EmailAttachment{{File: bytes.NewReader([]byte(reportBuilder.String())), Title: fmt.Sprintf("%s-check-report.txt", bucketName)}},
// }); err != nil {
// panic(fmt.Errorf("error while send email: %w", err))
// }
},
}