aboutsummaryrefslogtreecommitdiff
path: root/readConfig.c
blob: 5c09957866392862e4cf8a95f66dbff4637d9a8f (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
#include <stdlib.h>
#include <stdio.h>
#include <wordexp.h>
#include <string.h>
#include "config.h"

config_t config = { .SMS_INBOX = "",
                    .SMS_SENTBOX = "",
                    .SMS_OUTBOX = "",
                    .MMS_DIR = "",
                    .CONTACT_FILENAME = ""};

const char* search_key[]= {"SMS_INBOX", "SMS_SENTBOX", "SMS_OUTBOX", "CONTACT_FILENAME", "MMS_DIR"};

int searchConfigFile(char* configFile) {
    // Search a config file.
    // First then in the home, then in /etc and finaly in /var.
    // In debug mode, this function search in ./fixtures

    strcpy(configFile, "/home/ache/.mesmsrc");

    return 0;
}
int readConfigFile(void) {
    char fileName[256] = "";

#ifdef DEBUG
    fprintf(stderr, "ReadConfig\n");
#endif

    if( searchConfigFile(fileName) > 0 ) {
        return 1;
    }

    FILE* file = fopen(fileName, "r");
    char line[300] = "";

    if( file ) {
        while(fgets(line, 300, file) != NULL) {

            char* tmp = strrchr(line, '\n');
            if( tmp ) *tmp = 0;

            int elem = -1;
            for( int i = 0 ; i < sizeof search_key / sizeof *search_key ; i++) {
                if( strncmp(line, search_key[i], strlen(search_key[i])) == 0 ) {
                    elem = i;
                    break;
                }
            }
            if(elem >= 0) {
                char* res = NULL;
                if(strchr(line, '\"')) {
                    strtok(line, "\"");
                    res = strtok(NULL, "\"");
                } else if(strchr(line, '=')) {
                    strtok(line, "=");
                    res = strtok(NULL, "=");
                } else {
                    continue;
                }
                char* configProperty = ((char*[]){config.SMS_INBOX, config.SMS_SENTBOX,
                                            config.SMS_OUTBOX, config.MMS_DIR, config.CONTACT_FILENAME})[elem];
                int r = 0;

                if( !res ) res = "";
                if( strlen(res) > 255 ) continue;
                wordexp_t p;
                r = wordexp(res, &p, 0);

                if( r == 0) {
                    if( p.we_wordc > 0 )
                        strncpy( configProperty, p.we_wordv[0], 255);
                    wordfree(&p);
                } else {
                    strncpy( configProperty, res, 255);
                }
#ifdef DEBUG
                fprintf(stderr, "%s is \"%s\"\n", search_key[elem], configProperty );
#endif
            }
        }
    }
#ifdef DEBUG
    else {
        fprintf(stderr, "Error reading config file [%s]\n", fileName);
    }
#endif
}