1// SPDX-FileCopyrightText: 2022 Amolith <amolith@secluded.site>
 2//
 3// SPDX-License-Identifier: BSD-2-Clause
 4
 5package main
 6
 7import (
 8	"log"
 9	"os"
10
11	yaml "gopkg.in/yaml.v2"
12)
13
14// parseConfig takes the path to a config file as its own argument, attempts to
15// parse it and write the values to the internal config struct, and exits with
16// an error if it fails.
17func (m *model) parseConfig(configFile *string) {
18	configBytes, err := os.ReadFile(*configFile)
19	if err != nil {
20		log.Println("Config file not found, writing default values to", *flagConfig)
21		err = writeDefaultConfig(*flagConfig)
22		if err != nil {
23			log.Fatal("Error creating default config:", err)
24		}
25		os.Exit(0)
26	}
27	err = yaml.Unmarshal(configBytes, m)
28	if err != nil {
29		log.Fatalln("Error parsing config file:", err)
30	}
31}
32
33// writeDefaultConfig takes a config file path as its argument and writes the
34// default config to that path
35func writeDefaultConfig(configFile string) error {
36	file, err := os.Create(configFile)
37	if err != nil {
38		return err
39	}
40	defer file.Close()
41
42	_, err = file.WriteString("listen: 127.0.0.1:1313\naccessToken: CHANGEME\ndatabasePath: badger_db\n")
43	if err != nil {
44		return err
45	}
46	return nil
47}