summaryrefslogtreecommitdiff
path: root/main.go
blob: 55425e4a27750967c9eed541d21662028e17fafb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package main

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

	"xengineering.eu/ceres/model"
)

func main() {
	flag.Parse()

	if flags.version {
		fmt.Println(version)
		os.Exit(0)
	}

	log.Println("Ceres recipe server started")
	defer log.Println("Ceres recipe server stopped")
	log.Printf("Version: %s", version)

	if flags.config != "" {
		config.Read(flags.config)
	}

	storage := model.NewStorage(config.StorageFilePath)
	if !storage.Exists() {
		storage.Create()
	}
	log.Printf("Storage directory: %s\n", storage.Path)

	db, err := model.OpenDB(filepath.Join(storage.Path, "ceres.sqlite3"))
	if err != nil {
		log.Fatalf("Failed to open database: %v", err)
	}
	defer func() {
		err := db.Close()
		if err != nil {
			log.Println("Failed to close database")
		} else {
			log.Println("Closed database")
		}
	}()

	err = db.Migrate()
	if err != nil {
		log.Fatal(err)
	}

	if flags.examples {
		err := db.CreateExamples()
		if err != nil {
			log.Fatalf("Failed to insert example recipes: %v", err)
		}
		log.Println("Created example recipes")
	}

	server := NewServer(config.HttpAddress, db)
	go server.Start()
	defer server.Stop()

	await(syscall.SIGTERM, syscall.SIGINT)
}

func await(signals ...syscall.Signal) {
	listener := make(chan os.Signal)
	for _, s := range signals {
		signal.Notify(listener, s)
	}
	sig := <-listener
	log.Printf("Received OS signal '%v'\n", sig)
}