package main

import (
	"log"
	"os/exec"
	"time"

	"github.com/dietsche/rfsnotify"

	"git.kemonine.info/PiFrame/config"
	"git.kemonine.info/PiFrame/watchdog"
)

const (
	CMD_SYSTEMCTL = "/usr/bin/systemctl"
	TIMEOUT       = 5 * time.Second
)

func main() {
	// Load the config file
	pfConfig, configFileProvider := config.LoadConfig(false)

	// Watch for config changes and re-load config if needed
	configFileProvider.Watch(func(event interface{}, err error) {
		if err != nil {
			log.Printf("Error setting up watch of config : %s", err)
			return
		}

		// Bail on slideshow if there is a config change so it restarts with updated config
		log.Fatalf("Config file changed! Exiting!")
	})

	PATH_PICTURES := pfConfig.String(config.CONFIG_KEY_ALBUMS_ROOT)

	// Create watchdog timer that restarts pf-ui.service on timeout
	watchdog := watchdog.New(TIMEOUT, func() {
		err := exec.Command(CMD_SYSTEMCTL, "restart", "pf-ui.service").Run()
		if err != nil {
			log.Fatalf("Error running %s : %s", CMD_SYSTEMCTL, err)
		}
	})
	watchdog.DeferredStart()

	// Create fswatcher
	watcher, err := rfsnotify.NewWatcher()
	if err != nil {
		log.Fatal("Error setting up rfsnotify")
	}

	// Ensure we clean stuff up no matter what
	defer watcher.Close()

	// Setup goroutine and listen for events
	done := make(chan bool)
	go func() {
		for {
			select {
			case _, ok := <-watcher.Events:
				if !ok {
					return
				}
				// [Re]Start timer to restart slideshow after the fs events die down
				watchdog.Kick()
			case err, ok := <-watcher.Errors:
				if !ok {
					return
				}
				log.Println("Error: ", err)
			}
		}
	}()

	// Setup paths to watch
	err = watcher.AddRecursive(PATH_PICTURES)
	if err != nil {
		log.Fatalf("Error setting up recursive watch of %s", PATH_PICTURES)
	}

	// Drain done channel...
	<-done
}
