/*
 * 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_systemutils.h"
#include <buildboxcommon_logging.h>
#include <buildboxworker_logstreamdebugutils.h>

#include <sys/types.h>
#include <unistd.h>
#include <vector>

void buildboxworker::LogStreamDebugUtils::populateResourceNameArguments(
    const std::string &stdoutResourceName,
    const std::string &stderrResourceName, std::string *commandString)
{
    static const std::string stdoutPlaceholder = "{stdout}";
    static const std::string stderrPlaceholder = "{stderr}";

    findAndReplace(stdoutPlaceholder, stdoutResourceName, commandString);
    findAndReplace(stderrPlaceholder, stderrResourceName, commandString);
}

void buildboxworker::LogStreamDebugUtils::launchDebugCommand(
    const std::string &commandString, const std::string &stdoutResourceName,
    const std::string &stderrResourceName)
{
    if (!commandString.empty() &&
        (!stdoutResourceName.empty() || !stderrResourceName.empty())) {
        std::string command(commandString);
        populateResourceNameArguments(stdoutResourceName, stderrResourceName,
                                      &command);

        BUILDBOX_LOG_DEBUG("Launching LogStream debug command [" << command
                                                                 << "]");

        std::vector<std::string> cmd;
        cmd.emplace_back("sh");
        cmd.emplace_back("-c");
        cmd.emplace_back(command.c_str());

        const int exitCode =
            buildboxcommon::SystemUtils::executeCommandWithResult(cmd)
                .d_exitCode;

        BUILDBOX_LOG_DEBUG("LogStream debug command ["
                           << command.data() << "] returned: " << exitCode);
    }
}

void buildboxworker::LogStreamDebugUtils::findAndReplace(
    const std::string &pattern, const std::string &replacement, std::string *s)
{
    auto pos = s->find(pattern);
    while (pos != std::string::npos) {
        s->replace(pos, pattern.size(), replacement);
        pos = s->find(pattern, pos + pattern.size());
    }
}
