/*
 * 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_digestgenerator.h>
#include <buildboxcommon_fileutils.h>
#include <buildboxcommon_protos.h>

#include <span>

using buildboxcommon::Digest;

/**
 * This small CLI utility uploads a directory to a CAS server.
 * (It is intended for testing only.)
 *
 * If the upload is successful, prints a line with the root digest to stdout
 * and exits with status code 0. Otherwise exits with 1.
 */

void printUsage(char *program_name)
{
    std::cout << "Usage: " << program_name
              << " CASD_SERVER_ADDRESS INPUT_DIRECTORY\n"
              << "Uploads the given directory to the CAS server and prints "
                 "the digest of the root\n";
}

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;
    }

    buildboxcommon::DigestGenerator::init();

    const std::string casd_server_address = std::string(args[1]);
    const std::string input_path = std::string(args[2]);

    if (!buildboxcommon::FileUtils::isDirectory(input_path.c_str())) {
        std::cerr << "Error: input path \"" << input_path
                  << "\" is not a directory.\n";
        return 1;
    }

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

        // Uploading:
        std::cerr << "Uploading \"" << input_path << "\"...";
        Digest root_digest;
        cas_client.uploadDirectory(input_path, &root_digest);
        std::cerr << " done.\n";

        std::cout << root_digest << '\n';

        return 0;
    }
    catch (const std::exception &e) {
        std::cerr << "Upload failed: " << e.what() << '\n';
        return 1;
    }
}
