#include <maps/wikimap/mapspro/services/tasks_realtime/src/acl_roles_dumper/lib/acl_roles_dumper.h>

#include <maps/libs/log8/include/log8.h>
#include <yandex/maps/pgpool3utils/pg_advisory_mutex.h>
#include <yandex/maps/wiki/common/default_config.h>
#include <yandex/maps/wiki/common/pg_advisory_lock_ids.h>
#include <yandex/maps/wiki/common/pgpool3_helpers.h>

#include <cstdlib>

namespace {

const std::string ACL_ROLES_DUMP_PATH = "/config/services/acl/roles-dump";

} // namespace

using namespace maps;
using namespace maps::wiki;
using namespace maps::wiki::common;
using namespace maps::wiki::acl_roles_dumper;

int
main()
try {
    const auto servicesCfg = loadDefaultConfig();
    auto aclPoolHolder = PoolHolder(*servicesCfg, "core", "grinder");

    pgp3utils::PgAdvisoryXactMutex guard(
        aclPoolHolder.pool(),
        static_cast<int64_t>(AdvisoryLockIds::ACL_ROLES_DUMPER));
    if (!guard.try_lock()) {
        INFO() << "ACL roles are dumping already. (DB is locked)";
        return EXIT_SUCCESS;
    }

    auto aclTxnHandle = aclPoolHolder.pool().slaveTransaction();
    dump(aclTxnHandle.get(), servicesCfg->get<std::string>(ACL_ROLES_DUMP_PATH));

    return EXIT_SUCCESS;
} catch (const Exception& e) {
    FATAL() << "ACL roles dumper has failed: '" << e << "'.";
    return EXIT_FAILURE;
} catch (const std::exception& e) {
    FATAL() << "ACL roles dumper has failed: '" << e.what() << "'.";
    return EXIT_FAILURE;
}
