#include "main.hpp"
#include "ssl.hpp"
#include "imap.hpp"
#include "config.hpp"


int main(int argc, char** argv) {
    bool ask_pass = true;
    bool interactive = false;
    bool verify = true;
    if (argc < 2) {
        LOG(
            "usage: %s [--interactive|--batch] [--no-check-certificate] config\n"
            "       interactive: confirm before moving\n"
            "       batch: don't ask for passwords if empty\n"
            "       no-check-certificate: don't try to verify server certificate",
            argv[0]
        );
        return 1;
    }
    for (int i=1; i<argc-1; ++i) {
        if (!strcmp(argv[i], "--interactive")) {
            if (!ask_pass) return 1;
            interactive = true;
        } else if (!strcmp(argv[i], "--batch")) {
            if (interactive) return 1;
            ask_pass = false;
            close(0);
            close(1);
        } else if (!strcmp(argv[i], "--no-check-certificate")) {
            verify = false;
        } else {
            LOG("unknown option '%s'", argv[i]);
            return 1;
        }
    }

    Config config;
    if (!config.parse(argv[argc-1])) {
        return 1;
    }

    if (!SSLConn::init()) return 1;
    for (std::map<std::string, Config::server_t>::const_iterator it = config.servers.begin(); it != config.servers.end(); ++it) {
        const Config::server_t& server = it->second;
        if (server.tasks.empty()) continue;

        LOG("connecting to %s...", server.host.c_str());
        int fd = SSLConn::get_fd(server.host.c_str(), server.port.c_str());
        if (fd == -1) { if (interactive || ask_pass) continue; else return 1; }

        SSLConn* conn = new SSLConn();
        if (!conn->set_fd(fd, verify? server.host.c_str(): NULL)) {
            delete conn;
            if (interactive || ask_pass) continue; else return 1;
        }

        IMAP* imap = new IMAP(conn);
        if (!imap->init(ask_pass, server.user.c_str(), server.pass.c_str())) {
            delete imap;
            if (interactive || ask_pass) continue; else return 1;
        }
        for (std::vector<Config::agenda_t>::const_iterator tit = server.tasks.begin(); tit != server.tasks.end(); ++tit) {
            if (!imap->handle(interactive, tit->from.c_str(), config.matches.find(tit->match_id)->second.c_str(), tit->to.c_str())) {
                delete imap;
                if (interactive || ask_pass) continue; else return 1;
            }
        }
        delete imap;
    }

    return 0;
}