package main

import (
	"encoding/json"
	"fmt"
	"github.com/fsnotify/fsnotify"
	"log"
	"os"
	"os/signal"
	"syscall"
)

func main() {
	ReadOSTemplate("C:\\Users\\lx\\GolandProjects\\demo3\\filewatch\\ipxe_template.json")
	go MonitorDirectory("C:\\Users\\lx\\GolandProjects\\demo3\\filewatch\\ipxe_template.json")
	interruptChan := make(chan os.Signal, 1)

	// 注册信号处理
	signal.Notify(interruptChan, os.Interrupt, syscall.SIGTERM)

	// 等待信号
	<-interruptChan

}

var OSScript = make(map[string]string)

// MonitorDirectory 监视文件更改
func MonitorDirectory(dirPath string) {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}
	defer watcher.Close()

	done := make(chan bool)

	go func() {
		for {
			select {
			case event, ok := <-watcher.Events:
				if !ok {
					return
				}
				fmt.Println("event:", event)
				if event.Op&fsnotify.Write == fsnotify.Write {
					ReadOSTemplate(dirPath)
				}
			case err, ok := <-watcher.Errors:
				if !ok {
					return
				}
				fmt.Println("error:", err)
			}
		}
	}()

	// 添加需要监视的目录路径
	if err := addSubdirectories(watcher, dirPath); err != nil {
		log.Fatal(err)
	}
	<-done
}

func addSubdirectories(watcher *fsnotify.Watcher, dirPath string) error {

	if err := watcher.Add(dirPath); err != nil {
		return err
	}

	return nil
}

func ReadOSTemplate(dirPath string) {
	jsonFile, err := os.ReadFile(dirPath)
	if err != nil {
		log.Println("Error reading file:", err)
		return
	}
	err = json.Unmarshal(jsonFile, &OSScript)
	if err != nil {
		log.Println("Error reading file:", err)
		return
	}
	fmt.Println("OS Script:", OSScript)
}
