package main

import (
	"log"
	"os"
	"path/filepath"

	"github.com/fsnotify/fsnotify"
)

const (
	maxSize = 500 * 1024 * 1024 // 500MB
	logDir  = "/var/log"
)

func checkAndTruncate(filePath string) {
	fileInfo, err := os.Stat(filePath)
	if err != nil {
		log.Printf("获取文件信息失败 %s: %v", filePath, err)
		return
	}

	if fileInfo.Size() > maxSize {
		err := os.Truncate(filePath, 0)
		if err != nil {
			log.Printf("截断文件失败 %s: %v", filePath, err)
		} else {
			log.Printf("成功截断文件 %s", filePath)
		}
	}
}

func main() {
	// 初始检查所有文件
	files, err := os.ReadDir(logDir)
	if err != nil {
		log.Fatalf("读取日志目录失败: %v", err)
	}

	for _, file := range files {
		if file.IsDir() {
			continue
		}
		checkAndTruncate(filepath.Join(logDir, file.Name()))
	}

	// 创建文件监控
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatalf("创建文件监控失败: %v", err)
	}
	defer watcher.Close()

	err = watcher.Add(logDir)
	if err != nil {
		log.Fatalf("添加监控目录失败: %v", err)
	}

	log.Println("开始监控日志目录", logDir)
	for {
		select {
		case event := <-watcher.Events:
			if event.Op&fsnotify.Write == fsnotify.Write {
				checkAndTruncate(event.Name)
			}
		case err := <-watcher.Errors:
			log.Printf("监控错误: %v", err)
		}
	}
}
