summaryrefslogtreecommitdiff
path: root/main.c
blob: 6c50983d59e3062145c3ab4f0f059af095807966 (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
/*
 qotdserver
Copyright (C) 2019 Richard Knight

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "ini.h"
#include "qotdserver.h"
#include "logger.h"


void signal_handler(int sig){
    switch(sig){
        case SIGTERM:
            clean_db();
            write_log("SIGTERM received");
            close_logger();
            exit(0);
            break;
        case SIGKILL:
            clean_db();
            write_log("SIGKILL received");
            close_logger();
            exit(0);
            break;
    }
}

static int config_handler(void *user, const char *section, const char *name, 
                            const char *value) 
{
    Config *cnf = (Config*)user;
    
    #define MATCH(s, n) strcmp(section, s) == 0 && strcmp(name, n) == 0

    if (MATCH("database", "user")) {
        cnf->db_user = strdup(value);
    } else if (MATCH("database", "password")) {
        cnf->db_pass = strdup(value);
    } else if (MATCH("database", "host")) {
        cnf->db_host = strdup(value);
    } else if (MATCH("database", "name")) {
        cnf->db_name = strdup(value);
    } else if (MATCH("general", "daily")) {
        cnf->daily = atoi(value);
    } else {
        return 0;
    }
    return 1;
}


int main(int argc, char** argv) 
{
    signal(SIGTERM, signal_handler);
    signal(SIGKILL, signal_handler);
    
    char *conf_path = "/etc/qotdserver.conf";
    
    
    if (ini_parse(conf_path, config_handler, &config) < 0) {
        printf("Can't load configuration file %s\n", conf_path);
        return (EXIT_FAILURE);
    }
    
    if (!init_logger(&config)) {
        printf("Can't open log file for writing\n");
        return (EXIT_FAILURE);
    }
    
    if (!db_connect(&config)) {
        return (EXIT_FAILURE);
    }
   
    write_log("Starting server");
    
    daemon(0, 0);
    serve();
        
}