package main

import (
	"local/lastn/lastn"
	"local/rssmon3/config"
	"local/rssmon3/handlers"
	"local/rssmon3/monitor"
	"local/rssmon3/server"
	"log"
	"os"
	"os/signal"
	"path/filepath"
	"syscall"
	"time"
)

func main() {
	log.SetPrefix("..")
	time.Local = time.FixedZone("UTC-6", (-6*int(time.Hour))/int(time.Second))
	sigc := make(chan os.Signal)

	if err := config.New(); err != nil {
		panic(err)
	}
	log.Println("[main]", config.Values())

	m, err := monitor.New()
	if err != nil {
		panic(err)
	}
	go InterruptAfter(m.Run, sigc)

	s := server.New(m.Incoming)
	if err := s.Routes(); err != nil {
		panic(err)
	}
	go InterruptAfter(s.Run, sigc)

	h := handlers.New(m.Outgoing)
	go InterruptAfter(h.Run, sigc)

	go EnqueueBackups()

	signal.Notify(sigc,
		syscall.SIGHUP,
		syscall.SIGINT,
		syscall.SIGTERM,
		syscall.SIGQUIT,
	)
	<-sigc
	config.Values().Can()
	config.Values().DB.Close()
}

func InterruptAfter(foo func() error, c chan os.Signal) {
	if err := foo(); err != nil {
		log.Println("[InterruptAfter]", err)
	}
	c <- syscall.SIGINT
}

func EnqueueBackups() {
	realpath, err := filepath.Abs(config.Values().Addr)
	if err != nil {
		log.Println("dir", config.Values().Addr, "not found, so no backups")
		return
	}
	conf := lastn.Config{
		N:         3,
		Root:      realpath,
		Ns:        "backups",
		Store:     "files",
		StoreAddr: 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)
	}
	if err := lastn.Clean(); err != nil {
		log.Println("backup clean 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)
		}
	}
}
