<reponame>Gowa2017/ssdb<filename>cli/main.cpp
#include "ssdb/ssdb.h"
#include "util/config.h"
#include "util/string_util.h"
#include <iostream>
#include <map>
#include <string>
#include <stdio.h>
#include <sstream>
#include "main.h"
#include "cmd.h"
std::map<std::string, fn> CMDS;

SSDB *opendb() {
    char conf_file[1024];
    sprintf(conf_file, "%s/bin/ssdb.conf", getenv("HOME"));
    Config *conf = Config::load(conf_file);
    if (!conf) {
        fprintf(stderr, "error loading conf file: '%s'\n", conf_file);
        exit(1);
    }
    {
        std::string conf_dir = real_dirname(conf_file);
        if (chdir(conf_dir.c_str()) == -1) {
            fprintf(stderr, "error chdir: %s\n", conf_dir.c_str());
            exit(1);
        }
    }
    Options option;
    option.load(*conf);
    std::string data_db_dir = conf->get_str("leveldb.datadir");
    SSDB       *db          = NULL;
    db                      = SSDB::open(option, data_db_dir);
    if (!db) {
        fprintf(stderr, "could not open data db: %s\n", data_db_dir.c_str());
        exit(1);
    }
    return db;
}

void init() {
    REG(set);
    REG(get);
    REG(del);
    REG(clear);
    REG(scan);
    REG(list);
    REG(info);
    REG(copy);
    REG(rename);
}

int main(int argc, char **argv) {
    if (argc < 2) {
        fprintf(stderr, "ERROR: No command\n");
        return 1;
    }
    init();
    auto it = CMDS.find(argv[1]);
    if (it == CMDS.end()) {
        std::cout << "Unknown command: " << it->first << "\nYou can use:\t"
                  << std::endl;
        for (auto &&c : CMDS) { std::cout << c.first << " "; }
        std::cout << std::endl;
        return 1;
    }
    std::string cmd = it->first;
    fn          f   = it->second;
    if (cmd == "-h") {
        std::cout << "You can use:\t" << std::endl;
        for (auto &&c : CMDS) { std::cout << c.first << " "; }
        std::cout << std::endl;
        return 0;
    }
    SSDB                    *db = opendb();
    std::vector<std::string> args;
    for (size_t i = 2; i < argc; i++) { args.push_back(argv[i]); }
    f(db, args);

    return 0;
}
