package main

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

	_ "github.com/mattn/go-sqlite3"

	"git.luj0ga.de/franconian/matrix"
	"git.luj0ga.de/luca/matrix-prometheus/internal/config"
	"git.luj0ga.de/luca/matrix-prometheus/internal/webhook"
)

func main() {
	conf := config.FromEnv()

	db, err := sql.Open("sqlite3", conf.Db)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	client, err := matrix.NewClient(&conf.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 := webhook.NewServer(client)

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

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