/*
 * Copyright 2018 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.
 */

#ifndef BUILDBOXRUN_HOSTTOOLS
#define BUILDBOXRUN_HOSTTOOLS

#include <buildboxcommon_fileutils.h>
#include <buildboxcommon_runner.h>

#include <optional>
#include <string>
#include <unordered_map>

namespace buildboxcommon {
namespace buildboxrun {
namespace hosttools {

class HostToolsRunner : public Runner {
  public:
    /**
     * The simplest possible working runner: runs a job directly on your
     * machine as the current user without making any attempt to sandbox it.
     */
    ActionResult execute(const Command &command, const Digest &inputRootDigest,
                         const Platform &platform) override;

    // Parse custom arguments for this runner
    bool parseArg(std::string_view arg) override;

    // Print usage for the additional arguments supported by this runner in
    // parseArg
    void printSpecialUsage() override;

    // Check if this runner will allow running a given executable
    // If the allow list is empty, all executables are allowed
    bool executableInAllowedExecutables(const std::string &executable) const;

    // Public for testing purposes
    std::vector<std::string>
    generateCommandLine(const Command &command,
                        const std::string &stage_path) const;

    // Only for testing purposes
    std::optional<std::unordered_map<std::string, std::string>>
    getEnvironment() const;

    const std::optional<std::string> &getActionDigestEnv() const;

  private:
    bool d_prefix = false;
    std::set<std::string> d_allowedExecutables;
    // Configured base environment. The environment variables from the Command
    // will be set on top of this.
    std::optional<std::unordered_map<std::string, std::string>> d_environment;
    // If set, the action digest will be stored in this environment variable.
    std::optional<std::string> d_actionDigestEnv;

    void setUpEnvironment(const Command &command) const;
    void createParentDirectories(const Command &command,
                                 const std::string &workingDir) const;
};

} // namespace hosttools
} // namespace buildboxrun
} // namespace buildboxcommon
#endif
