package main

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

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

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()
		}
	}
	wg := sync.WaitGroup{}
	wg.Add(2)
	go logic.StartSftpMonitor(&wg)
	go logic.StartAuditMonitor(&wg)
	ctx, cancel := context.WithCancel(context.Background())
	go func(c context.Context) {
		ticker := time.NewTicker(time.Minute * 5)
		defer ticker.Stop()
		for {
			select {
			case <-ticker.C:
				logic.CleanSCP()
				logic.CleanSftp()
			case <-c.Done():
				return
			}
		}
	}(ctx)
	wg.Wait()
	cancel()
}
