aboutsummaryrefslogtreecommitdiff
path: root/src/init.c
blob: 0dbeada8ed9d787e7635c1b4b562d6d330269cc3 (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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <kore/kore.h>
#include <kore/pgsql.h>

int init_db(void);
void kore_parent_configure(int, char **);

static const char *database = "db";

void
kore_parent_configure(int argc, char **argv)
{
	int err = 0;

	kore_default_getopt(argc, argv);

	err = init_db();
	if (err != KORE_RESULT_OK) {
		kore_log(LOG_ERR, "Error registering the database.");
		// FIXME How to terminate?
		exit(1);
	}
}

int
init_db(void)
{
	int err = 0;
	const char *env = NULL;
	struct kore_buf *pg_config_buf = kore_buf_alloc(0);

	// Parse env vars and build PostgreSQL config string
	env = getenv("POSTGRES_HOST");
	if (env)
	{
		kore_buf_appendf(pg_config_buf, "host=%s ", env);
	}
	else
	{
		const char *host = "host=localhost ";
		kore_buf_append(pg_config_buf, host, strlen(host));
	}

	env = getenv("POSTGRES_PORT");
	if (env)
	{
		kore_buf_appendf(pg_config_buf, "port=%s ", env);
	}
	else
	{
		const char *port = "port=5432 ";
		kore_buf_append(pg_config_buf, port, strlen(port));
	}

	env = getenv("POSTGRES_USER");
	if (env)
	{
		kore_buf_appendf(pg_config_buf, "user=%s ", env);
	}
	else
	{
		const char *user = "user=clog ";
		kore_buf_append(pg_config_buf, user, strlen(user));
	}

	env = getenv("POSTGRES_PASSWORD");
	if (env)
	{
		kore_buf_appendf(pg_config_buf, "password=%s ", env);
	}
	
	env = getenv("POSTGRES_DBNAME");
	if (env)
	{
		kore_buf_appendf(pg_config_buf, "user=%s ", env);
	}
	else
	{
		const char *dbname = "dbname=clog ";
		kore_buf_append(pg_config_buf, dbname, strlen(dbname));
	}

	// FIXME: Should be configurable.
	const char *sslmode = "sslmode=disable ";
	kore_buf_append(pg_config_buf, sslmode, strlen(sslmode));

	// Register the database
	const char *pg_config = kore_buf_stringify(pg_config_buf, NULL);
	kore_log(LOG_INFO, "%s", pg_config);
	err = kore_pgsql_register(
		database,
		pg_config
	);

	kore_buf_free(pg_config_buf);

	return err;
}