/*
* Copyright (C) 2024 Jonni Liljamo <jonni@liljamo.com>
*
* This file is licensed under AGPL-3.0-or-later, see NOTICE and LICENSE for
* more information.
*/
// Package db implements database migrations and manipulation utilities.
package db
import (
"database/sql"
"log/slog"
"git.src.quest/~liljamo/felu/internal/config"
// nolint
_ "github.com/mattn/go-sqlite3"
)
// DBConn is a global for accessing the database connection.
var DBConn *sql.DB
// InitDB initializes the programs database.
func InitDB() error {
var err error
DBConn, err = sql.Open("sqlite3",
config.FeluConfig.DataDir+"felu.db?_foreign_keys=true")
if err != nil {
return err
}
runMigrations()
return nil
}
// InitAdminUser initializes the programs admin user.
//
// Errors out if at least one admin user already exists.
func InitAdminUser() error {
rows, err := DBConn.Query(`SELECT id FROM users WHERE is_admin = TRUE`)
if err != nil {
return err
}
defer rows.Close()
if rows.Next() {
// There is at least one...
slog.Info("Existing admin user found")
return nil
}
// Since we're here, it's assumed no admin accounts exist
slog.Info("Creating initial admin user")
err = CreateAdmin(config.FeluConfig.InitialAdminEmail, config.FeluConfig.InitialAdminPwd)
if err != nil {
return err
}
return nil
}