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

#ifndef INCLUDED_BUILDBOXRUN_COMMANDFILEMANAGER
#define INCLUDED_BUILDBOXRUN_COMMANDFILEMANAGER

#include <buildboxcommon_protos.h>
#include <buildboxcommon_temporaryfile.h>
#include <string>

namespace buildboxcommon {
namespace buildboxrun {
namespace userchroot {

class CommandFileManager {

  public:
    /*
     * The constructor will create a file at file_location.
     * This file will export all the command's environment variables.
     * It will then cd into the working directory specified by the command.
     * Following this, the file will delete itself, and then run the
     * command's arguments.
     */
    CommandFileManager(const Command &command,
                       const std::string &chroot_location,
                       const std::string &location_in_chroot,
                       const std::string &file_prefix);

    /*
     * Return the path to file inside the chroot
     */
    std::string getFilePathInChroot() const;

    /*
     * Return the path to file outside the chroot
     */
    std::string getAbsoluteFilePath() const;

    ~CommandFileManager() = default;

    CommandFileManager(const CommandFileManager &) = delete;
    CommandFileManager &operator=(const CommandFileManager &) = delete;
    CommandFileManager(CommandFileManager &&) = delete;
    CommandFileManager &operator=(CommandFileManager &&) = delete;

  private:
    const Command d_command;

    // location inside chroot
    std::string d_file_abs_path_in_chroot;

    // location on disk
    std::string d_file_abs_path;

    std::unique_ptr<TemporaryFile> d_tmp_command_file;

    void writeCommandToFile();
};

} // namespace userchroot
} // namespace buildboxrun
} // namespace buildboxcommon

#endif
