/*
 * Copyright 2020 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 <regex>
#include <span>

using buildboxcommon::Digest;

/**
 * This small CLI utility fetches a directory to a CAS server.
 * (It is intended for testing only.)
 *
 * If the fetch operation is successful exits with status code 0, otherwise
 * with 1.
 */

void printUsage(char *program_name)
{
    std::cout << "Usage: " << program_name
              << " CASD_SERVER_ADDRESS DIRECTORY_DIGEST\n"
              << "Issues a LocalCas.FetchTree() request to pull the given "
                 "directory and its contents into local storage.\n";
}

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

    static 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[])
{
    auto args = std::span(argv, argc);

    // Parsing arguments:
    if (argc < 3) {
        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]);

    try {
        const Digest directory_digest =
            digest_from_string(std::string(args[2]));

        // 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();

        // Fetching:
        std::cerr << "Calling FetchTree(root_digest=" << directory_digest
                  << ", fetch_file_blobs=true) from \"" + casd_server_address +
                         "\"...";

        cas_client.fetchTree(directory_digest, true);
        std::cerr << " done.\n";
        return 0;
    }
    catch (const std::exception &e) {
        std::cerr << "FetchTree() failed: " << e.what() << '\n';
        return 1;
    }
}
