package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"os/signal"

	"gopkg.in/urfave/cli.v1"

	"ur.gs/crockery/internal/services"
	"ur.gs/crockery/internal/store"
)

func crockeryRun(c *cli.Context) error {
	db := c.GlobalString("db")
	ctx, cancel := context.WithCancel(context.Background())

	if db == "" {
		return fmt.Errorf("No crockery database file specified")
	}

	log.Printf("Loading config from file %q", db)

	datastore, err := store.New(context.Background(), db)
	if err != nil {
		return err
	}

	defer datastore.Close()

	if datastore.Domain() == "" {
		return fmt.Errorf("No domain configured in file %q", db)
	}

	if _, err := datastore.FindAccount("postmaster@" + datastore.Domain()); err != nil {
		return fmt.Errorf("Couldn't find postmaster: %v", err)
	}

	log.Printf("Starting crockery for domain %q", datastore.Domain())

	srv, err := services.New(ctx, datastore)
	if err != nil {
		return fmt.Errorf("Couldn't start services:", err)
	}

	sig := make(chan os.Signal, 1)
	done := make(chan bool)

	signal.Notify(sig, os.Interrupt)

	go func() {
		s := <-sig
		log.Print("Got signal: ", s)
		cancel()
	}()

	go func() {
		srv.Run()
		close(done)
	}()

	<-done

	log.Println("All services finished, exiting")

	return nil
}
