package main

import (
	"flag"
	"log"
	"os"
	"os/signal"
	"path"
	"syscall"

	"golang.org/x/oauth2/clientcredentials"
	"gopkg.in/fsnotify.v1"
)

var (
	TeamsDir        string
	skipInitialSync bool
)

func main() {
	if v, exists := os.LookupEnv("ZQDS_BASEURL"); exists {
		base_URL = v
	}
	if v, exists := os.LookupEnv("ZQDS_EVENTID"); exists {
		eventId = v
	}
	if v, exists := os.LookupEnv("ZQDS_ROUNDID"); exists {
		roundId = v
	}

	var clientId string
	if v, exists := os.LookupEnv("ZQDS_CLIENTID"); exists {
		clientId = v
	}
	var clientSecret string
	if v, exists := os.LookupEnv("ZQDS_CLIENTSECRET"); exists {
		clientSecret = v
	}
	if v, exists := os.LookupEnv("ZQDS_TOKENURL"); exists {
		TokenURL = v
	}

	flag.StringVar(&TeamsDir, "teams", "./TEAMS", "Base directory where save teams JSON files")
	var debugINotify = flag.Bool("debuginotify", false, "Show skipped inotofy events")
	flag.BoolVar(&skipInitialSync, "skipinitialsync", skipInitialSync, "Skip the initial synchronization")
	flag.Parse()

	log.SetPrefix("[scores-sync-zqds] ")

	TeamsDir = path.Clean(TeamsDir)

	configOauth = clientcredentials.Config{
		ClientID:     clientId,
		ClientSecret: clientSecret,
		Scopes:       []string{"score:update"},
		TokenURL:     TokenURL,
	}

	log.Println("Registering directory events...")
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}
	defer watcher.Close()

	if err := watcher.Add(TeamsDir); err != nil {
		log.Fatal(err)
	}

	if !skipInitialSync {
		if _, err := os.Stat(path.Join(TeamsDir, "teams.json")); err == nil {
			treatAll(path.Join(TeamsDir, "teams.json"))
		}
	}

	// Register SIGUSR1, SIGUSR2
	interrupt := make(chan os.Signal, 1)
	signal.Notify(interrupt, syscall.SIGHUP)

	watchedNotify := fsnotify.Create

	for {
		select {
		case <-interrupt:
			log.Println("SIGHUP received, resyncing all teams' score...")
			treatAll(path.Join(TeamsDir, "teams.json"))
			log.Println("SIGHUP treated.")
		case ev := <-watcher.Events:
			if path.Base(ev.Name) == "teams.json" {
				if ev.Op&watchedNotify == watchedNotify {
					if *debugINotify {
						log.Println("Treating event:", ev, "for", ev.Name)
					}
					go treatDiff(ev.Name)
				} else if ev.Op&fsnotify.Write == fsnotify.Write {
					log.Println("FSNOTIFY WRITE SEEN. Prefer looking at them, as it appears files are not atomically moved.")
					watchedNotify = fsnotify.Write
					go treatDiff(ev.Name)
				} else if *debugINotify {
					log.Println("Skipped teams.json event:", ev)
				}
			} else if *debugINotify {
				log.Println("Skipped NON teams.json event:", ev, "for", ev.Name)
			}
		case err := <-watcher.Errors:
			log.Println("error:", err)
		}
	}
}
