package main

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

	"github.com/gofrs/flock"
)

// 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
)

func init() {
	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)
	}
}

func shutdown() {
	if logfile != nil {
		logfile.Close()
	}
}

func main() {
	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)
	}
	logic.StartSftpMonitor()
}
