//	utf-8

/*	Copyright  (c)	Günter Woigk   2001-2003
  					mailto:kio@little-bat.de

	This file is free software

 	This program is distributed in the hope that it will be useful,
 	but WITHOUT ANY WARRANTY; without even the implied warranty of
 	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  

 	Permission to use, copy, modify, distribute, and sell this software and
 	its documentation for any purpose is hereby granted without fee, provided
 	that the above copyright notice appear in all copies and that both that
 	copyright notice and this permission notice appear in supporting
 	documentation, and that the name of the copyright holder not be used
 	in advertising or publicity pertaining to distribution of the software
 	without specific, written prior permission. The copyright holder makes no
 	representations about the suitability of this software for any purpose.
 	It is provided "as is" without express or implied warranty.

 	THE COPYRIGHT HOLDER DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
 	INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
 	EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY SPECIAL, 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.

	2003-08-15 kio	fixed buggy call to ioctl() in SetBlocking() and SetAsync()
*/

#define	SAFE	3
#define	LOG		1

#include	"config.h"
#include	<unistd.h>
#include	<sys/stat.h>
#include	<stdio.h>
#include	<sys/param.h>
#include	<stdlib.h>
#include	<fcntl.h>
#include	<sys/ioctl.h>
#include	<termios.h>
#include	"file_utilities.h"



/* ---- set/clear blocking io -----------
		=> errno EAGAIN wenn input empty/output full
*/
void SetBlocking ( int fd, bool onoff )
{
	int arg = fcntl(fd,F_GETFL,&arg);
	if (arg==-1) return; // errno set
	if (onoff) arg &= ~O_NONBLOCK; else arg |= O_NONBLOCK;
	fcntl(fd,F_SETFL,arg);
}

/* ----	set/clear async io mode ----------
		=> signal SIGIO wenn input available/output possible
		***???*** lt. dt. man page geht das mit fcntl() nicht!
		***!!!*** lt. engl. man page geht es.
*/
void SetAsync ( int fd, bool onoff )
{
	int arg = fcntl(fd,F_GETFL,&arg);
	if (arg==-1) return; // errno set
#if defined(_SOLARIS)
	NIMP();
#else
	if (onoff) arg |= O_ASYNC; else arg &= ~O_ASYNC;
#endif
	fcntl(fd,F_SETFL,arg);
}


void SetBlocking ( FILE* file, bool onoff )	{ SetBlocking(fileno(file), onoff); }
void SetAsync    ( FILE* file, bool onoff )	{ SetAsync   (fileno(file), onoff); }



/* ---- modification date of file ------------------
*/
time_t FileMTime ( cstr path )
{
	struct stat fs;
	stat(path,&fs);
#if !defined(_POSIX_SOURCE) && !defined(_SOLARIS)
//	timespec& ts = fs.st_atimespec;   // last access time
	timespec& ts = fs.st_mtimespec;   // last modification time
//	timespec& ts = fs.st_ctimespec;   // last status change time
	return ts.tv_sec;
#else
	return fs.st_mtime;               // last modification time
#endif
}


/* ---- last access date of file ------------------
*/
time_t FileATime ( cstr path )
{
	struct stat fs;
	stat(path,&fs);
#if !defined(_POSIX_SOURCE) && !defined(_SOLARIS)
	timespec& ts = fs.st_atimespec;	// last access time
//	timespec& ts = fs.st_mtimespec; // last modification time
//	timespec& ts = fs.st_ctimespec; // last status change time
	return ts.tv_sec;
#else
	return fs.st_atime;             // last modification time
#endif
}



s_type ClassifyFile ( mode_t mode )
{
	if (S_ISREG (mode)) return s_file;  else	// File
	if (S_ISFIFO(mode)) return s_pipe;  else	// Pipe
	if (S_ISDIR (mode)) return s_dir;   else	// Directory
	if (S_ISBLK (mode)) return s_block; else	// Block device
	if (S_ISSOCK(mode)) return s_sock;  else	// Socket
	if (S_ISLNK (mode)) return s_link;  else	// Symbolic link
#if !defined(_POSIX_SOURCE) && !defined(_SOLARIS)
	if (S_ISWHT (mode)) return s_null;  else	// White out
#endif
	if (S_ISCHR (mode)) return s_tty;   else	// Character special
	return s_unkn;
}


s_type ClassifyFile ( cstr filepath )
{
	if (!filepath) return s_none;

	struct stat data;
	if (stat(filepath, &data)) return s_unkn;
	else return ClassifyFile(data.st_mode);
}


s_type ClassifyFile ( int fd )
{
	if (fd<0) return s_none;

//	OSErr err=errno;						// isatty() sets errno
//	if (isatty(fd)) return s_tty;
//	errno=err;

	struct stat data;
	if (fstat(fd, &data)) return s_unkn;	// note: fstat follows a sym link
	else return ClassifyFile(data.st_mode);
}


s_type ClassifyFile( FILE* file )
{
	if (file) return ClassifyFile(fileno(file));
	else return s_none;
}


off_t FileLength ( cstr path )
{	struct stat fs;
	if (!path||!*path) return 0;
	if (stat(path,&fs)) return 0;			// error
	return fs.st_size;
}

off_t FileLength ( int fd )
{	struct stat fs;
	if (fd<0) return 0;
	if (fstat(fd,&fs)) return 0;			// error
	return fs.st_size;
}

off_t FileLength ( FILE* file )
{	struct stat fs;
	if (!file) return 0;
	if (fstat(fileno(file),&fs)) return 0;	// error
	return fs.st_size;
}



/* ----	separate filename from partial/absolute path ----------------------
		returned string may point into passed path argument
*/
cstr FileNameFromPath ( cstr name )
{
	XXTRAP(!name);
	cstr tf = strrchr(name,'/'); 
	if(tf) return tf+1; else return name;
}


/* ----	separate filename extension from path -----------------------------
		returned string may point into passed path argument
*/
cstr ExtensionFromPath ( cstr name )
{
	name = FileNameFromPath(name);
	cstr dot = strrchr(name,'.');
	if( dot && strlen(dot)<=4+1 ) return dot+1; else return "";
}


/* ----	separate filename basename from path ------------------------------
		returned string may be in cstring pool
		returned string may point into passed path argument
*/
cstr BasenameFromPath ( cstr name )
{
	name = FileNameFromPath(name);
	cstr dot = strrchr(name,'.');
	if( dot && strlen(dot)<=4+1 ) return SubStr(name,dot); else return name;
}


cstr DirectoryPathFromPath ( cstr name )
{
	XXTRAP(!name);
	cstr tf = strrchr(name,'/'); 
	if(tf) return SubStr(name,tf+1); else return "./";	
}


cstr FullPath ( cstr path )
{
	if (!path) path="";
	if (path[0]=='~'&&(path[1]==0||path[1]=='/'))
	{
		cstr home = getenv("HOME");
		if (home) path = CatStr(home,MidStr(path,1));
	}
	char s[MAXPATHLEN];
	realpath(path,s);			// may set errno
	return DupStr(s);			// return copy in string pool	
}


/* ----	provide a temp file name --------------
		temp file must be renamable to file.
*/
cstr TempFileName ( cstr file )
{
	return CatStr(file,"~");
}



// ioctl -> tty control
// tcgetattr/tcsetattr -> tty control

void TerminalSize ( int tty, uint& rows, uint& cols )
{
	XXXTRAP(Error());
	struct winsize data;
	ioctl ( tty, TIOCGWINSZ, &data );
	rows = data.ws_row;
	cols = data.ws_col;
	XXXTRAP(Error());
}

uint TerminalRows ( int tty )
{
	struct winsize data;
	ioctl ( tty, TIOCGWINSZ, &data );
	return data.ws_row;
}

uint TerminalCols ( int tty )
{
	struct winsize data;
	ioctl ( tty, TIOCGWINSZ, &data );
	return data.ws_col;
}

uint TerminalWidth ( int tty )
{
	struct winsize data;
	ioctl ( tty, TIOCGWINSZ, &data );
	return data.ws_xpixel;
}

uint TerminalHeight ( int tty )
{
	struct winsize data;
	ioctl ( tty, TIOCGWINSZ, &data );
	return data.ws_ypixel;
}

/* funzt ned.
void SetTerminalSize(int tty, uint cols, uint rows )
{
	struct winsize data;
	ioctl ( tty, TIOCGWINSZ, &data );
	data.ws_xpixel = data.ws_xpixel/data.ws_col*cols;
	data.ws_ypixel = data.ws_ypixel/data.ws_row*rows;
	data.ws_row = rows;
	data.ws_col = cols;
	ioctl ( tty, TIOCSWINSZ, &data );
}
*/









