/*
 * 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_CHROOTMANAGER
#define INCLUDED_BUILDBOXRUN_CHROOTMANAGER

#include <buildboxrun_commandfilemanager.h>

#include <buildboxcommon_protos.h>

#include <string>
#include <vector>

namespace buildboxcommon {
namespace buildboxrun {
namespace userchroot {

class ChrootManager {
  public:
    /*
     * Will attempt to install devices
     * Throw error on failure
     */
    ChrootManager(const std::string &userchroot_bin,
                  const std::string &root_path, const std::string &sudoBin,
                  const std::string &user);

    /*
     * Will attempt to uninstall devices.
     */
    ~ChrootManager();

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

    /*
     * Generate command line argument using userchroot
     * The command line will have userchroot invoke a shell subprocess
     * which will execute a file containing all the relevant commands.

     * This method will also create the file to be executed, and place it into
     * the chroot in the tmp directory.
     */
    const std::vector<std::string> generateCommandLine(const Command &command);

  private:
    // location of userchroot binary
    const std::string d_userchroot_bin;

    // location of chroot
    const std::string d_root_path;

    // location of userchroot binary
    const std::string d_sudoBin;
    // Run as user
    const std::string d_user;

    // location of command file in chroot
    static const std::string s_command_file_location;

    // command file prefix
    static const std::string s_command_file_prefix;

    std::unique_ptr<CommandFileManager> d_command_file;
    enum class Device { INSTALL, UNINSTALL };

    /*
     * fork & exec userchroot command to install/uninstall
     * devices. Returns true if command successful, false otherwise
     */
    bool chrootDeviceCommand(Device device_command);
};

} // namespace userchroot
} // namespace buildboxrun
} // namespace buildboxcommon
#endif
