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

#include <buildboxrun_hosttools_changedirectoryguard.h>

#include <buildboxcommon_exception.h>
#include <buildboxcommon_logging.h>

#include <cstring>
#include <exception>
#include <limits.h>
#include <string>
#include <system_error>
#include <unistd.h>

namespace buildboxcommon {
namespace buildboxrun {
namespace hosttools {

ChangeDirectoryGuard::ChangeDirectoryGuard(const std::string &directory)
{
    char buff[PATH_MAX];
    if (getcwd(buff, sizeof(buff)) == nullptr) {
        BUILDBOXCOMMON_THROW_SYSTEM_EXCEPTION(
            std::system_error, errno, std::system_category,
            "Unable to get the current working directory");
    }

    d_previousDirectory = std::string(buff);

    if (chdir(directory.c_str()) == -1) {
        BUILDBOXCOMMON_THROW_SYSTEM_EXCEPTION(
            std::system_error, errno, std::system_category,
            "Unable to change into directory \"" << directory << "\"");
    }
}

ChangeDirectoryGuard::~ChangeDirectoryGuard()
{
    if (chdir(d_previousDirectory.c_str()) == -1) {
        BUILDBOX_LOG_ERROR("Unable to return to previous directory ["
                           << d_previousDirectory
                           << "] on destruction: " << std::strerror(errno));
    }
}
} // namespace hosttools
} // namespace buildboxrun
} // namespace buildboxcommon
