//$ g++ copy_file_test.cpp -lboost_filesystem -o copy_file
//$ ./copy_file /tmp/.private/$USER /home/$USER

#include <boost/filesystem.hpp>
#include <iostream>

using namespace std;

int main(int argc, char** argv) {
	if (argc < 3) {
		cerr << "Укажите исходную и целевую директории" << endl;
		cerr << argv[0] << " [исходная директория] [целевая директория]" << endl;
		return EXIT_FAILURE;
	}

	string paths[2];
	for (size_t i = 1; i < 3; ++i) {
		if (!boost::filesystem::is_directory (argv[i])) {
			cerr << "'" << argv[i] << "' должна быть существующей директорией" << endl;
			return EXIT_FAILURE;
		}

		paths[i - 1] = (boost::filesystem::path (argv[i]) / "TestFile.txt").string();
	}

	

	ofstream tempFile (paths[0], ofstream::out);
	tempFile << "Lorem ipsum dolor sit amet" << endl;
	tempFile.close();

	if (rename (paths[0].c_str(), paths[1].c_str()) == 0) {
		cerr << "Исходная и целевая директории размещены на одном устройстве" << endl;
		remove (paths[1].c_str());
		return EXIT_FAILURE;
	}

	if (errno != EXDEV) {
		cerr << "Произошла другая ошибка при копировании файла: " << strerror(errno) << endl;
		remove (paths[0].c_str());
		return EXIT_FAILURE;
	}
	
	try {
		boost::filesystem::copy_file (paths[0], paths[1], boost::filesystem::copy_options::overwrite_existing);
		for (size_t i = 0; i < 2; ++i)
			remove (paths[i].c_str());
		cout << "Тест завершился успешно!" << endl;
		return EXIT_SUCCESS;
	} catch (boost::filesystem::filesystem_error &ex) {
		for (size_t i = 0; i < 2; ++i)
			remove (paths[i].c_str());
		cerr << "Тест завершился неудачей: " << ex.what() << endl;
		return EXIT_FAILURE;
	}
}

