package main

import (
	"context"
	"log"
	"os"
	"os/signal"
	"sync"
	"syscall"

	"git.luj0ga.de/franconian/matrix-pretix/internal/config"
	"git.luj0ga.de/franconian/matrix-pretix/internal/database"
	"git.luj0ga.de/franconian/matrix-pretix/internal/matrix"
	"git.luj0ga.de/franconian/matrix-pretix/internal/pretix"
)

func main() {
	if len(os.Args) != 2 {
		log.Fatal("missing config file path")
	}

	config, err := config.ParseFromFile(os.Args[1])
	if err != nil {
		log.Fatal(err)
	}

	db, err := database.Open(&config.DB)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	client, err := matrix.NewClient(&config.Matrix, db)
	if err != nil {
		log.Fatal(err)
	}

	err = client.Login()
	if err != nil {
		log.Fatal(err)
	}

	err = client.Encrypt()
	if err != nil {
		log.Fatal(err)
	}

	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()

	var wg sync.WaitGroup
	go func() {
		wg.Add(1)
		defer wg.Done()

		<-ctx.Done()

		stop()
	}()

	go client.Sync(ctx, stop, &wg)

	server := pretix.NewServer(&config.Server, db, client)

	err = server.ListenAndServe(ctx, &wg)
	if err != nil {
		stop()
		wg.Wait()
		log.Fatal(err)
	}

	wg.Wait()
	log.Print("done")
}
