///
/// \file enoent.cc
/// \author kyle 
/// \created 2023-10-11
/// \brief basic file system checks
///
/// \section COPYRIGHT
/// Copyright 2023 K. Isom <kyle@imap.cc>
///
/// Permission to use, copy, modify, and/or distribute this software for
/// any purpose with or without fee is hereby granted, provided that the
/// above copyright notice and this permission notice appear in all copies.
///
/// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
/// WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
/// WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
/// BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
/// OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
/// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
/// ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
/// SOFTWARE.
///
#include <algorithm>
#include <iostream>
#include <iterator>
#include <fstream>
#include <filesystem>
#include <vector>


using namespace std;


int
main()
{
	namespace fs = std::filesystem;

	std::string          input = "ohai\n";
	std::vector<uint8_t> buffer(input.begin(), input.end());
	auto                 f     = fs::path("ENOENT2");

	if (fs::exists(f)) {
		std::cout << "[+] the file exists\n";
		std::cout << "\tfile size: " << fs::file_size(f) << "\n";
	} else {
		std::cout << "the file does not exist\n";
	}
	cout << "[+] attempting to open the file.\n";
	ofstream handle(f, std::ios::in | std::ios::out | std::ios::trunc);

	if (!handle.good()) {
		cerr << "[!] file operation failed\n";
		cerr << "\tfile fail: " << handle.fail() << "\n";
		cerr << "\t file eof: " << handle.eof() << "\n";
		cerr << "\t file bad: " << handle.bad() << "\n";
		return 1;
	}

	if (fs::exists(f)) {
		std::cout << "[+] the file exists\n";
		std::cout << "\tfile size: " << fs::file_size(f) << "\n";
	} else {
		std::cout << "the file does not exist\n";
	}
	handle.flush();
	if (fs::exists(f)) {
		std::cout << "[+] the file exists\n";
		std::cout << "\tfile size: " << fs::file_size(f) << "\n";
	} else {
		std::cout << "the file does not exist\n";
	}
	cout << "[+] file open successfully. attempting to write.\n";
	handle << "Hello, world.\r\n";

	if (fs::exists(f)) {
		std::cout << "\tfile size: " << fs::file_size(f) << "\n";
	}

	cout << "[+] attempting to write the vector to file.\n";

	std::copy(buffer.begin(), buffer.end(), std::ostream_iterator<uint8_t>(handle, ""));

	cout << "[+] closing the file.\n";
	handle.close();

	if (fs::exists(f)) {
		std::cout << "\tfile size: " << fs::file_size(f) << "\n";
	}

	return 0;

}