/*
 * Copyright 2019 Bloomberg Finance LP
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <buildboxcommon_casclient.h>
#include <buildboxcommon_fileutils.h>
#include <buildboxcommon_protos.h>

#include <atomic>
#include <csignal>
#include <exception>
#include <iostream>
#include <regex>
#include <span>
#include <system_error>
#include <unistd.h>

using buildboxcommon::Digest;

/**
 * This small CLI utility stages a path using the LocalCAS protocol.
 * (It is intended for testing only.)
 *
 * It will issue a `StageTree()` request and wait for a signal to close the
 * connection, indicating to the server to clean the stage directory, before
 * proceeding to exit.
 */

void signal_handler(int signum)
{
    std::cout << "Received signal " << signum << ", finishing.\n";
}

void printUsage(char *program_name)
{
    std::cout
        << "Usage: " << program_name
        << " CASD_SERVER_ADDRESS ROOT_DIRECTORY_DIGEST STAGE_DIRECTORY\n";
}

Digest digest_from_string(const std::string &s)
{
    // "[hash in hex notation]/[size_bytes]"

    static const std::regex regex("([0-9a-fA-F]+)/(\\d+)");

    std::smatch matches;
    if (std::regex_search(s, matches, regex) && matches.size() == 3) {
        const std::string hash = matches[1];
        const std::string size = matches[2];

        Digest d;
        d.set_hash(hash);
        d.set_size_bytes(std::stoll(size));
        return d;
    }

    throw std::invalid_argument("Could not parse a digest from the string.");
}

int main(int argc, char *argv[])
{
    try {
        auto args = std::span(argv, argc);

        // Parsing arguments:
        if (argc < 4) {
            std::cerr << "Error: missing arguments.\n";
            printUsage(args[0]);
            return -1;
        }

        // initializing digest generator
        buildboxcommon::DigestGenerator::init();

        const std::string casd_server_address = std::string(args[1]);
        const Digest root_directory_digest =
            digest_from_string(std::string(args[2]));
        const std::string stage_directory = std::string(args[3]);

        // Connecting to CAS server:
        std::cout << "CAS client connecting to " << casd_server_address
                  << '\n';
        auto grpc_client = std::make_shared<buildboxcommon::GrpcClient>();
        buildboxcommon::CASClient cas_client(grpc_client);
        buildboxcommon::ConnectionOptions connection_options;
        connection_options.d_url = casd_server_address.c_str();
        grpc_client->init(connection_options);
        cas_client.init();

        // Staging:
        std::cout << "Staging \"" << toString(root_directory_digest)
                  << "\"...";
        const auto staged_directory = cas_client.stage(
            root_directory_digest,
            buildboxcommon::StageTreeRequest_StagingMode_DEFAULT,
            stage_directory);
        std::cout << " done. \n";

        std::cout << "Directory staged in \"" << staged_directory->path()
                  << "\"\n";

        // Block waiting for a signal before ending the connection and exiting:

        // Setup signal handlers for SIGINT and SIGTERM
        struct sigaction sa{};
        sa.sa_handler = signal_handler;
        sigemptyset(&sa.sa_mask);
        sa.sa_flags = 0;

        if (sigaction(SIGINT, &sa, nullptr) == -1) {
            BUILDBOX_LOG_ERROR("Unable to register signal handler for SIGINT");
        }
        if (sigaction(SIGTERM, &sa, nullptr) == -1) {
            BUILDBOX_LOG_ERROR(
                "Unable to register signal handler for SIGTERM");
        }
        pause();

        std::cout << "Unstaging and exiting.\n";
        return 0;
    }
    catch (const std::exception &exception) {
        // This catch should not be relied on and is here as a backstop.
        BUILDBOX_LOG_ERROR("Caught exception in main " << exception.what());
        return 1;
    }
}
