#include <maps/wikimap/mapspro/services/mrc/drive/firmware_updater/storage/lib/configuration.h>
#include <maps/wikimap/mapspro/services/mrc/drive/firmware_updater/storage/lib/error_reporter.h>
#include <maps/wikimap/mapspro/services/mrc/drive/firmware_updater/libs/config/include/config.h>

#include <maps/infra/yacare/include/yacare.h>
#include <maps/infra/yacare/include/tvm.h>
#include <maps/libs/auth/include/blackbox.h>
#include <maps/libs/auth/include/tvm.h>
#include <maps/libs/cmdline/include/cmdline.h>
#include <maps/libs/log8/include/log8.h>

#include <maps/libs/common/include/exception.h>

#include <memory>
#include <string>

using namespace maps::fw_updater;

const yacare::VirtualHost VHOST{
    yacare::VirtualHost::SLB {
        "core-firmware-storage",
        "firmware-storage"
    },
    yacare::VirtualHost::FQDN {
        "core-firmware-storage.maps.yandex.net",
        "core-firmware-storage.testing.maps.yandex.net",
    },
};

YCR_SET_DEFAULT(VHOST);


YCR_MAIN(argc, argv) try {
    maps::cmdline::Parser parser;
    auto configPath = parser.string("config")
            .help("path to configuration file");
    auto secretVersion = parser.string("secret-version")
            .help("version for secrets from yav.yandex-team.ru");
    auto disableTvmClient = parser.flag("disable-tvm")
            .defaultValue(false)
            .help("disable tvm client");

    parser.parse(argc, argv);

    if (!disableTvmClient) {
        yacare::tvm::configureUserAuth(
            maps::auth::BlackboxApi(maps::auth::TvmtoolSettings())
        );
    }

    INFO() << "Starting";
    const auto cfg = config::templateConfigFromCmdPath(secretVersion, configPath);

    storage::Configuration::swap(storage::makeConfiguration(std::move(cfg)));

    yacare::setErrorReporter(storage::errorReporter);
    yacare::run();

    INFO() << "Shutting down";
    return EXIT_SUCCESS;
}
catch (const maps::Exception& e) {
    ERROR() << e;
    return EXIT_FAILURE;
}
catch (const std::exception& e) {
    ERROR() << e.what();
    return EXIT_FAILURE;
}
