server/remote/scores-sync-zqds/main.go

110 lines
2.6 KiB
Go
Raw Normal View History

2021-09-05 03:27:36 +00:00
package main
import (
"flag"
"log"
"os"
"os/signal"
"path"
"syscall"
"golang.org/x/oauth2/clientcredentials"
2021-09-05 03:27:36 +00:00
"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
2021-09-05 03:27:36 +00:00
if v, exists := os.LookupEnv("ZQDS_CLIENTID"); exists {
clientId = v
}
var clientSecret string
2021-09-05 03:27:36 +00:00
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,
}
2021-09-05 03:27:36 +00:00
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"))
}
2021-09-05 03:27:36 +00:00
}
// 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" {
2021-09-05 03:27:36 +00:00
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)
2021-09-05 03:27:36 +00:00
} 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)
}
}
}