/*
 * 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_HOSTTOOLS_CHANGEDIRECTORYGUARD
#define INCLUDED_HOSTTOOLS_CHANGEDIRECTORYGUARD

#include <string>

namespace buildboxcommon {
namespace buildboxrun {
namespace hosttools {

class ChangeDirectoryGuard {
    /***
     * ChangeDirectoryGuard is a simple RAII guard that records the current
     * directory, changes into a new directory, and on destruction attempts to
     * switch back to the original directory.
     */
  private:
    std::string d_previousDirectory;

  public:
    /**
     * Switch into the given directory and save the current directory
     * to d_previousDirectory. Will throw std::system_error if getcwd or chdir
     * fails
     */
    ChangeDirectoryGuard(const std::string &directory);

    /**
     * Change into the directory stored in d_previousDirectory. Since this is
     * in the destructor an exception will not be thrown when chdir fails.
     * Instead a message is logged at ERROR level
     */
    ~ChangeDirectoryGuard();

    ChangeDirectoryGuard(const ChangeDirectoryGuard &) = delete;
    ChangeDirectoryGuard &operator=(const ChangeDirectoryGuard &) = delete;
    ChangeDirectoryGuard(ChangeDirectoryGuard &&) = delete;
    ChangeDirectoryGuard &operator=(ChangeDirectoryGuard &&) = delete;
};

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