summaryrefslogtreecommitdiff
path: root/src/main.c
blob: 5f1a7cbf88015653bed4ed22ad821ddea09c2c1f (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
99
100
101
102
103
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "cmd.h"
#include "include/mdb.h"

int getid(char *selector);
int printkeys(tablist_t *list, int id, char **keys, int klen);
void printkey(tabidx_t idx);

int main(int argc, char **argv) {
	if (argc > 2) {
		printf("usage: %s [db file]\n", argv[0]);
		exit(1);
	}
	char *filename = NULL;
	if (argc == 2)
		filename = argv[1];
	tablist_t *list = readdb(filename);
	if (list == NULL)
		exit(1);
	char *cmd = calloc(1024, sizeof(char));

	while (fgets(cmd, 1024, stdin) != NULL) {
		cmd[strlen(cmd) - 1] = '\0';
		if (!strcmp(cmd, "exit") || !strcmp(cmd, ""))
			break;
		struct cmd evaled = eval(cmd);
		int id = getid(evaled.selector);
		switch (evaled.type) {
		case GET:
			printkeys(list, id, evaled.params, evaled.plen);
			break;
		case SET:
			id = setkeys(&list, id, evaled.params, evaled.plen);
			if (!id && filename)
				writedb(filename, list);
			break;
		case DEL:
			id = delkeys(list, id, evaled.params, evaled.plen);
			if (!id && filename)
				writedb(filename, list);
			break;
		case ERR:
			fprintf(stderr, "Unkown command: %s\n", cmd);
			break;
		}
		if (evaled.params != NULL) {
			for (int i = 0; i < evaled.plen; ++i)
				free(evaled.params[i]);
			free(evaled.params);
		}
		free(evaled.selector);
	}
	free(cmd);

	delkeys(list, -1, NULL, 0);
	free(list);
	exit(0);
}

int getid(char *selector) {
	if (selector == NULL)
		return -2;
	int id;
	if (!strcmp(selector, "*"))
		return -1;
	else if (isdigit(selector[0]) && (id = atoi(selector)) >= 0)
		return id;
	else
		return -2;
}

int printkeys(tablist_t *list, int id, char **keys, int klen) {
	tablist_t *indexes = getkeys(list, id, keys, klen);
	if (indexes == NULL)
		return 1;
	for (int i = 0; i < indexes[0].len; ++i) {
		printf("{ id: %d ", i);
		for (int j = 0; indexes[i].tab[j].flag; ++j)
			printkey(indexes[i].tab[j]);
		printf("}\n");
	}
	free(indexes);
	return 0;
}

void printkey(tabidx_t idx) {
	printf("%s: ", idx.key);
	switch (idx.flag) {
	case 1:
		printf("%.2lf ", idx.value.num);
		break;
	case 2:
		printf("%s ", idx.value.boolean ? "true" : "false");
		break;
	case 3:
		printf("%s ", idx.value.str);
		break;
	}
}