lunabot/src/journal/main.c

119 lines
2.7 KiB
C
Raw Normal View History

2019-04-27 05:37:22 +00:00
#include <stdio.h>
2019-04-27 06:49:04 +00:00
#include <string.h>
#include <stdlib.h>
2019-04-27 06:49:04 +00:00
2019-04-29 03:42:44 +00:00
#include "journal.h"
2019-04-27 06:49:04 +00:00
#define TOPICS 10
2019-04-27 05:37:22 +00:00
// go through all elements of argv[2] and beyond
// and join them together in a string
char *extract_handler_msg(int argc, char **argv)
{
int cur = 0;
// allocate an empty slot to start with.
char *res = malloc(cur);
// iterate through each argument
for(int i = 2; argv[i] != NULL; i++)
{
// catch it, get its length
char *word = argv[i];
int wordlen = strlen(word);
// increase the size of our current things by
// arg length + 1 (for a whitespace)
cur += wordlen;
res = realloc(res, cur + 1);
// only prepend our whitespace if we AREN'T
// at the first argument.
if(i != 2)
{
res[cur - wordlen] = ' ';
cur++;
}
// merge our current results with the current arg
for(int j = 0; j < wordlen; j++)
{
res[cur - wordlen + j] = word[j];
}
}
return res;
}
2019-04-27 05:37:22 +00:00
int main(int argc, char** argv)
{
if(argc < 2)
{
printf("usage: %s topic message\n", argv[0]);
return 0;
}
char *topic = argv[1];
2019-04-27 06:49:04 +00:00
2019-04-30 05:38:01 +00:00
// topics are injected at compile time
// yes, i'm keeping track of those. don't shame me :)))))
2019-04-27 06:49:04 +00:00
const char* topics[TOPICS] = {
2019-04-30 05:23:18 +00:00
"emotion", "lust", "orgasm"
2019-04-27 06:49:04 +00:00
};
// default handling by journal_write_topic is marked
// as the NULL values in this array.
2019-04-29 03:42:44 +00:00
void (*handlers[])(FILE*, char*) = {
2019-04-30 05:23:18 +00:00
NULL, NULL, NULL
2019-04-27 06:49:04 +00:00
};
2019-04-30 05:38:01 +00:00
if(STREQ(topic, "version"))
{
printf("lunabot journal v%s\n", JOURNAL_VERSION);
return 0;
}
// list all topics when arg1 is list
2019-04-30 05:38:01 +00:00
if(STREQ(topic, "list"))
{
for(int i = 0; topics[i] != NULL; i++)
printf("%s ", topics[i]);
printf("\n");
return 0;
}
2019-04-30 05:38:01 +00:00
// go through each topic to find which one we want
// to push the current entry to
for(int i = 0; topics[i] != NULL; i++)
2019-04-27 06:49:04 +00:00
{
const char* cur_topic = topics[i];
2019-04-29 03:42:44 +00:00
2019-04-27 06:49:04 +00:00
if(strcmp(topic, cur_topic) == 0)
{
2019-04-29 03:42:44 +00:00
void (*fun_ptr)(FILE*, char*) = handlers[i];
FILE* journal_file = journal_open(topic);
char *handler_message = extract_handler_msg(argc, argv);
printf("[%s] said '%s'\n", topic, handler_message);
if(fun_ptr == NULL) {
journal_write_topic(journal_file, topic, handler_message);
} else {
fun_ptr(journal_file, handler_message);
}
2019-04-29 03:42:44 +00:00
journal_close(journal_file);
free(handler_message);
printf("done!\n");
2019-04-27 06:49:04 +00:00
return 0;
}
}
printf("topic %s not found\n", topic);
2019-04-27 05:37:22 +00:00
return 0;
}