package main

import (
	"fmt"
	"log"
	"net"
	"os/exec"
	"sshd-tool/cmd/sftp-monitor/logic"
	"strings"

	"github.com/gofrs/flock"
)

const (
	SocketPath   = "/var/run/authpriv.sock"
	FileLockPath = "/tmp/sftp-monitor.pid"
)

func main() {
	fileLock := flock.New(FileLockPath, flock.SetPermissions(0644))
	l, err := fileLock.TryLock()
	if err != nil {
		log.Fatalf("error lock file %s, %v", fileLock, err)
	}
	if !l {
		log.Fatalf("can't lock %s, Perhaps an instance is already running.", FileLockPath)
	}

	// 删除旧
	_ = exec.Command("rm", "-f", SocketPath).Run()

	conn, err := net.ListenPacket("unixgram", SocketPath)
	if err != nil {
		log.Fatalf("can't listen unix socket: %v", err)
	}

	buff := make([]byte, 16384)
	for {
		n, _, err := conn.ReadFrom(buff)
		if err != nil {
			log.Fatalf("read error: %v", err)
			break
		}
		content := string(buff[:n])
		if strings.Contains(content, "sftp-server") {
			fmt.Println(content)
			go logic.HandleSftpLog(content)
		}
	}
}
