package main

import (
	"fmt"
	"log"
	"os"
	"sshd-tool/cmd/file-monitor/logic"
	"time"

	"github.com/gofrs/flock"
	"github.com/spf13/pflag"
)

// import (
// 	"fmt"
// 	"log"
// 	"os"
// 	"sshd-tool/cmd/file-monitor/logic"
// 	"time"

// 	"github.com/elastic/go-libaudit/v2"
// 	"github.com/elastic/go-libaudit/v2/aucoalesce"
// 	"github.com/elastic/go-libaudit/v2/auparse"
// )

// type EventHandler struct{}

// func (h *EventHandler) ReassemblyComplete(msgs []*auparse.AuditMessage) {
// 	event, err := aucoalesce.CoalesceMessages(msgs)
// 	if err != nil {
// 		fmt.Printf("coalesce messages error: %v", err)
// 	}
// 	logic.EventChan <- event
// }

// func (h *EventHandler) EventsLost(count int) {
// 	fmt.Fprintf(os.Stderr, "=== event lost: %d \n", count)
// }

// func main() {
// 	cli, err := libaudit.NewMulticastAuditClient(nil)
// 	if err != nil {
// 		log.Fatalf("failed to create audit client: %v", err)
// 	}
// 	defer cli.Close()

// 	handler := &EventHandler{}
// 	rea, err := libaudit.NewReassembler(1024, time.Second*60, handler)
// 	if err != nil {
// 		log.Printf("%v", err)
// 		return
// 	}
// 	defer rea.Close()

// 	go func() {
// 		ticker := time.NewTicker(time.Second * 15)
// 		defer ticker.Stop()
// 		for range ticker.C {
// 			if rea.Maintain() != nil {
// 				break
// 			}
// 		}
// 	}()

// 	go logic.FiltMsg()

// 	for {
// 		rawMsg, err := cli.Receive(false)
// 		if err != nil {
// 			break
// 		}
// 		_ = rea.Push(rawMsg.Type, rawMsg.Data)
// 	}

// 	close(logic.EventChan)
// }

var (
	logfile   *os.File
	flagDebug = pflag.Bool("debug", false, "debug mode, print log to stdout, not file")
	flagHelp  = pflag.BoolP("help", "h", false, "show usage")
)

func main() {
	pflag.Parse()

	if *flagHelp {
		fmt.Println("Monitor sftp and scp file uploads. After a file is uploaded, use clamdscan to scan the file. If the file contains a virus, delete it")
		pflag.Usage()
		return
	}

	fileLock := flock.New("/tmp/file-monitor.lock")
	locked, err := fileLock.TryLock()
	if err != nil || !locked {
		log.Fatal("there is already a file-monitor instance running, stopping")
	}
	defer fileLock.Unlock()
	err = logic.CheckExec()
	if err != nil {
		log.Fatal(err)
	}

	if !*flagDebug {
		logFile, err := os.Create(fmt.Sprintf("/var/log/file-monitor.%s.log", time.Now().Format("2006-01-02_15-04-05")))
		if err == nil {
			logfile = logFile
			log.SetOutput(logFile)
			defer logFile.Close()
		}
	}

	logic.StartSftpMonitor()
}
