/*

Copyright (c) 2002-2005, Yauheni Akhotnikau
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

- Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

- Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.

- The name of the author may not be used to endorse or promote products derived
from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.

*/

/*
	ObjESSty-1
*/
#include <cerrno>
#include <cstring>

#ifndef __unix__
#include <sys\types.h>
#include <sys\stat.h>
#include <share.h>
#include <io.h>
#else
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#endif

#include <stdio.h>

#include <fcntl.h>

// Those symbols is not defined on some platforms. Tanndem for example.
#if !defined( S_IREAD )
	#define S_IREAD 0400
#endif
#if !defined( S_IWRITE )
	#define S_IWRITE 0200
#endif

// Under UNIX O_BINARY is undefined.
#if !defined( O_BINARY )
	#define O_BINARY 0
#endif

#include <oess_1/defs/h/ex.hpp>

#include <oess_1/file/h/errno.hpp>

#include <oess_1/file/impl/h/filetool.hpp>

using namespace std;

namespace oess_1 {

namespace file {

namespace impl {

//
// auto_file_closer_t
//

/*!
	\brief Аналог auto_ptr для файла.

	Закрывает файл в деструкторе, если перед этим не было
	обращения к clear().
*/
class	auto_file_closer_t {
	private :
		int	m_file;
	public :
		inline
		auto_file_closer_t( int file ) : m_file( file ) {
		}

		inline
		~auto_file_closer_t() {
			if( -1 != m_file ) {
				close( m_file );
			}
		}

		inline int
		query() const {
			return m_file;
		}

		/*! Отказаться от автоматического закрытия файла. */
		inline void
		clear() {
			m_file = -1;
		}
};

int
open_and_lock( const oess_1::char_t * file_name,
	bool is_read_only ) {

	int file = open( file_name, O_BINARY |
			( is_read_only ? O_RDONLY : O_RDWR ) );
	if( -1 == file )
		OESS_THROW_PHYSIC( oess_1::file::err::c_cannot_open_file,
			"file: " << file_name
			<< ", is_read_only: " << is_read_only
			<< "; errno: " << errno
			<< ", strerror: " << strerror( errno ) )
	return file;
}

void
unlock_and_close( int file ) {
	close( file );
}

int
create_and_lock(
	const oess_1::char_t * file_name ) {

	// Пытаемся открыть файл.
	int file = open( file_name, O_BINARY | O_RDWR );
	if( -1 == file ) {
		// Файл открыть не удалось. Считаем, что его нет.
		file = open( file_name, O_BINARY | O_CREAT | O_RDWR,
			S_IREAD | S_IWRITE );
		if( -1 == file )
			OESS_THROW_PHYSIC( oess_1::file::err::c_cannot_create_file,
				"file: " << file_name
				<< "; errno: " << errno
				<< ", strerror: " << strerror( errno ) )
	}
	else {

		// Файл открыт. Нужно удалить содержимое.
		auto_file_closer_t fcloser( file );

		truncate_file( file, 0 );

		fcloser.clear();
	}

	return file;
}

void
truncate_file(
	int file, oess_1::uint_t size ) {

#ifdef __unix__
	if( -1 == ftruncate( file, size ) )
		OESS_THROW_PHYSIC( oess_1::file::err::c_cannot_truncate_file,
			"errno: " << errno
			<< ", strerror: " << strerror( errno ) )
#else
	if( -1 == chsize( file, size ) )
		OESS_THROW_PHYSIC( oess_1::file::err::c_cannot_truncate_file,
			"errno: " << errno
			<< ", strerror: " << strerror( errno ) )
#endif
}

void
remove_file( const oess_1::char_t * file_name )
{
	if( remove( file_name ) < 0 )
		OESS_THROW_PHYSIC( oess_1::file::err::c_cannot_remove_file,
			"remove_file('" << file_name << "'): "
			"errno: " << errno
			<< ", strerror: " << strerror( errno ) )
}

bool
is_file_exists( const oess_1::char_t * file_name )
{
	struct stat file_stat;
	if( !stat( file_name, &file_stat ) )
	{
		if( file_stat.st_mode & S_IFREG )
			return true;
	}

	return false;
}

} /* namespace impl */

} /* namespace file */

} /* namespace oess_1 */
