1// SPDX-FileCopyrightText: 2022 Amolith <amolith@secluded.site>
 2//
 3// SPDX-License-Identifier: BSD-2-Clause
 4
 5package main
 6
 7import (
 8	"embed"
 9	"log"
10	"net/http"
11	"net/http/pprof"
12
13	"github.com/dgraph-io/badger/v3"
14	flag "github.com/spf13/pflag"
15)
16
17//go:embed templates
18var templates embed.FS
19
20var flagConfig *string = flag.StringP("config", "c", "config.yaml", "Path to config file")
21
22type model struct {
23	Listen       string `yaml:"listen"`
24	AccessToken  string `yaml:"accessToken"`
25	DatabasePath string `yaml:"databasePath"`
26	database     *badger.DB
27}
28
29func (m *model) init() {
30	flag.Parse()
31	log.Println("Reading config at", *flagConfig)
32	m.parseConfig(flagConfig)
33	log.Println("Listening on", m.Listen)
34	if m.AccessToken == "CHANGEME" {
35		log.Fatalln("Access token *must* be changed.")
36	} else if m.AccessToken == "" {
37		log.Fatalln("Access token *must* be defined.")
38	}
39	log.Println("Reading database at", m.DatabasePath+"/")
40}
41
42func main() {
43	m := model{}
44	m.init()
45
46	db, err := badger.Open(badger.DefaultOptions(m.DatabasePath))
47	m.database = db
48	if err != nil {
49		log.Fatal(err)
50	}
51	defer m.database.Close()
52
53	mux := http.NewServeMux()
54
55	httpServer := &http.Server{
56		Addr:    m.Listen,
57		Handler: mux,
58	}
59
60	mux.HandleFunc("/", m.root)
61	mux.HandleFunc("/login", m.login)
62	mux.HandleFunc("/logout", m.logout)
63	mux.HandleFunc("/create", m.createHandler)
64	mux.HandleFunc("/read", m.readHandler)
65	mux.HandleFunc("/delete", m.deleteHandler)
66	mux.HandleFunc("/update", m.updateHandler)
67	mux.HandleFunc("/debug/pprof", pprof.Index)
68	mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
69	mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
70	mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
71	mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
72
73	if err = httpServer.ListenAndServe(); err == http.ErrServerClosed {
74		log.Println("Web server closed")
75	} else {
76		log.Fatalln(err)
77	}
78}