//go:build !windows && !plan9

package main

import (
	"bufio"
	"flag"
	"fmt"
	"log"
	"log/syslog"
	"os"
	"strings"
	"time"
)

func main() {
	var ip = flag.String("ip", "localhost:514", "ip:port")
	var cycle = flag.Int("cycle", 1000, "repeat number")
	var cycleSpan = flag.Int("sleep", 1, "sleep millisecond after one cycle")
	var span = flag.Int("span", 1, "sleep 1 millisecond every span row")
	var protocol = flag.String("protocol", "udp", "udp/tcp")
	var incTime = flag.Int("inctime", 1, "Increase seconds")
	var file = flag.String("file", "", "filenamesave for save")

	flag.Parse()

	var writer *bufio.Writer

	if *file != "" {
		// 创建输出文件
		outputFile, err := os.Create(*file)
		if err != nil {
			log.Fatal("无法创建输出文件:", err)
		}
		defer outputFile.Close()

		writer = bufio.NewWriter(outputFile)
		defer writer.Flush() // 确保所有缓冲数据写入磁盘
	}

	filePath := os.Args[len(os.Args)-1]
	readFile, err := os.Open(filePath)
	if err != nil {
		log.Fatal(err)
	}

	fileScanner := bufio.NewScanner(readFile)
	fileScanner.Split(bufio.ScanLines)
	var fileLines []string
	for fileScanner.Scan() {
		fileLines = append(fileLines, fileScanner.Text())
	}
	_ = readFile.Close()

	/*for _, line := range fileLines {
	      fmt.Println(line)
	  }

	  fmt.Println(fileLines)
	*/

	sysLog, err := syslog.Dial(*protocol, *ip, syslog.LOG_WARNING|syslog.LOG_DAEMON, "demo")
	if err != nil {
		log.Fatal(err)
	}

	// 11-Jul-2023 16:00:01 DNS systemd: Started Session 1370 of user root.
	format := "02-Jan-2006 15:04:05"
	total := 0
	loop := 0
	for i := 0; i < *cycle; i++ {
		incDuration := time.Second * time.Duration(i*(*incTime))
		for k, line := range fileLines {
			if *incTime != 0 && line != "" {
				fields := strings.Fields(line)
				if len(fields) > 2 {
					timeStr := fields[0] + " " + fields[1]
					line = strings.Join(fields[2:], " ")
					t, err := time.Parse(format, timeStr)
					if err != nil {
						log.Fatal(err)
					}
					t = t.Add(incDuration)
					line = t.Format(format) + " " + line
				}
			}

			if *file == "" {
				if err = sysLog.Emerg(line); err != nil {
					log.Fatal(err)
				}
			} else {
				// 将行内容写入输出文件（包括换行符）
				_, err := writer.WriteString(line + "\n")
				if err != nil {
					log.Fatal("写入文件失败:", err)
				}

				// 每处理100行刷新一次缓冲区（可选）
				if total%10 == 0 {
					writer.Flush()
				}

			}

			if *span > 0 && (k%*span == 0) {
				time.Sleep(time.Duration(*span) * time.Millisecond)
			}
			total++
		}
		loop++
		fmt.Printf("send %d , total %d row .\n", loop, total)
		if *cycleSpan > 0 {
			time.Sleep(time.Duration(*cycleSpan) * time.Millisecond)
		}
	}
}
