package main

import (
	"local/firestormy/config"
	"local/firestormy/scheduler"
	"local/firestormy/server"
	"local/lastn/lastn"
	"log"
	"net/http"
	"os"
	"os/signal"
	"path/filepath"
	"time"
)

func main() {
	var err error
	s := scheduler.New()
	if config.Config != "" {
		var err error
		s, err = scheduler.NewFromFile(config.Config)
		if err != nil {
			panic(err)
		}
	}
	err = s.Start()
	if err != nil {
		panic(err)
	}

	server := server.New()
	if err := server.Routes(); err != nil {
		panic(err)
	}

	//go EnqueueBackups()

	go func() {
		log.Printf("Serving on %q", config.Port)
		if err := http.ListenAndServe(config.Port, server); err != nil {
			panic(err)
		}
	}()

	// catch stop
	stop := make(chan os.Signal)
	signal.Notify(stop, os.Interrupt)
	<-stop
	s.Stop()
}

func EnqueueBackups() {
	realpath, err := filepath.Abs(config.StoreAddr)
	if err != nil {
		log.Println("dir", config.StoreAddr, "not found, so no backups")
		return
	}
	conf := lastn.Config{
		N:      3,
		Rclone: "/dev/null",
		Root:   realpath,
		Ns:     "backups",
		Store:  "files",
		Conf:   realpath + "-backups",
	}
	log.Printf("backups conf: %+v", conf)
	lastn, err := lastn.New(conf)
	if err != nil {
		log.Println("backups disabled:", realpath, ":", err)
		return
	}
	ticker := time.NewTicker(time.Hour * 24)
	log.Println("backup initial:", err)
	if err := lastn.Push(); err != nil {
		log.Println("backup failed:", err)
	}
	for _ = range ticker.C {
		log.Println("backing up...")
		if err := lastn.Push(); err != nil {
			log.Println("backup push failed:", err)
		}
		if err := lastn.Clean(); err != nil {
			log.Println("backup clean failed:", err)
		}
	}
}
