//	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()
	2003-10-09 kio	enhanced FullPath() to match broken utf-8 filenames
*/

#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"


/* ----	options --------------------------------------------------

	#ifdef	MATCH_INVALID_UTF8_PATHS				2003-10-09 kio
		=>	FullPath() also matches pathnames with broken utf-8 characters
*/



/* ---- 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); }


/* ---- stat() file --------------------------------
*/
static int stat ( cstr path, struct stat* buf, bool follow_symlink )
{
	return follow_symlink ? stat(path,buf) : lstat(path,buf);
}


/* ---- modification date of file ------------------
*/
time_t FileMTime ( cstr path, bool follow_symlink )
{
	struct stat fs;
	stat(path,&fs,follow_symlink);
	return M_TIME(fs);
}


/* ---- last access date of file ------------------
*/
time_t FileATime ( cstr path, bool follow_symlink )
{
	struct stat fs;
	stat(path,&fs,follow_symlink);
	return A_TIME(fs);
}


/* ---- last status change time of file ------------------
*/
time_t FileCTime ( cstr path, bool follow_symlink )
{
	struct stat fs;
	stat(path,&fs,follow_symlink);
	return C_TIME(fs);
}



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 path, bool follow_symlink )
{
	if (!path) return s_none;
	struct stat fs;
	if( stat(path,&fs,follow_symlink) ) return s_none;
	else return ClassifyFile(fs.st_mode);
}


s_type ClassifyFile ( int fd )
{
	if (fd<0) return s_none;
	struct stat data;
	if (fstat(fd, &data)) return s_none;
	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, bool follow_symlink )
{	struct stat fs;
	if (!path||!*path) return 0;
	if (stat(path,&fs,follow_symlink)) 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 path ---------------------------------------
		returned string points into passed path argument  ((guaranteed!))
		returned string is empty if path ended with '/'
*/
cstr FileNameFromPath ( cstr path )
{
	XXTRAP(!path);
	cstr p = strrchr(path,'/');
	return p ? p+1 : path;
}


/* ----	separate filename or last directory from path ---------------------
		returned string points into passed path argument  ((guaranteed!))
*/
cstr LastComponentFromPath ( cstr path )
{
	XXTRAP(!path);
	cstr p = strchr(path,0) -2;
	while( p>=path && *p!='/' ) { p--; }
	return p>=path ? p+1 : path;
}


/* ----	separate filename extension from path -----------------------------
		returned string points into passed path argument  ((guaranteed!))
		returned strings includes '.'
*/
cstr ExtensionFromPath ( cstr path )
{
	path = FileNameFromPath(path);
	cstr dot = strrchr(path,'.');
	cstr spc = strrchr(path,' ');
	if( dot>spc ) return dot; else return strchr(path,0);
}


/* ----	separate filename basename from path ------------------------------
		returns string in cstring pool
*/
cstr BasenameFromPath ( cstr path )
{
	path = FileNameFromPath(path);
	return SubStr( path, ExtensionFromPath(path) );
}


/* ----	separate directory path from path ------------------------------
		returns string in cstring pool
		returned string includes final '/'
		returns "./" instead of "" if passed path contains no '/'
*/
cstr DirectoryPathFromPath ( cstr path )
{
	path = SubStr( path, FileNameFromPath(path) );
	return *path ? path : "./";
}


#ifdef MATCH_INVALID_UTF8_PATHS
#include	<dirent.h>
#include	"ustring/sstring.h"
#include	"utf-8/utf-8.h"
/* ----	resolve broken UTF-8 filename -------------------------
		in: path = path to an existing directory
			file = file inside directory which could not be found
		out:
			corrected filename if file could be matched against an invalid utf-8 filename
			else NULL
*/
static cstr FindBrokenUTF8File ( cstr path, cstr file )
{
	DIR* dir = opendir(path);
	if (!dir) return NULL;		// errno set
	struct dirent* direntry;
	readdir(dir);	// skip ..
	readdir(dir);	// skip .
	while ((direntry=readdir(dir)))
	{
		cstr name = direntry->d_name;
	//	if( UTF8StrIsValid(name) ) continue;		***TODO*** optimize
		if( strcmp(String(name,iso_latin_1).CString(),file)==0 )
		{
			name = DupStr(name);
			closedir(dir);
			return name;
		}
	}
	closedir(dir);
	return NULL;
}
#endif


/* ---- real path ----------------------------------
		resolve partial paths
		resolve stuff like "//" and "./" and "../"
		resolve home directory
		resolve symbolic links
		resolve broken utf-8 filenames  ((option))
		no error for not present final path component
		=> assume directory/file will be created
		returned path has no trailing "/" except for rootdir == "/"
*/
cstr FullPath( cstr path, bool follow_symlink )
{	const int bu_size = MAXPATHLEN+256;
	char bu[bu_size];
	ptr lpath, k1, l_end, rpath, r_end;

	XXLogIn( "FullPath(\"%s\",%i)", path,follow_symlink );

	if (!path||!*path) path = ".";

	char c0=path[0], c1=path[1];

	if( c0=='~' && (c1==0||c1=='/') && (lpath=getenv("HOME")) )
	{
		strcpy(bu,lpath); strcat(bu,path+1);
	}

	else if( c0!='/' )
	{
		cstr wdpath = getcwd(bu,MAXPATHLEN);
		XXTRAP(!wdpath);
		XXTRAP(*wdpath!='/');
		strcat(bu,"/");
		strcat(bu,path);
	}
	else
	{
		strcpy(bu,path);
	}

	l_end = strchr(bu,0);
	while( l_end>bu && l_end[-1]=='/' ) l_end--;

	r_end = bu +bu_size;
	rpath = r_end - (l_end-bu);
	memmove( rpath, bu, l_end-bu);
	lpath = l_end = bu; 		// "/left/portion/of/path/": exists

	int lc = 33;				// link counter -> detect recursion

// *** doit ***

	for(;;)
	{
		ClearError();
		if( rpath>=r_end )  break;			// finished

	// split k1 from rpath
		if( l_end==lpath || l_end[-1]!='/' ) *l_end++ = '/';
		k1 = l_end;					// move current component from rpath to lpath
		while(rpath<r_end&&*rpath!='/') { *l_end++ = *rpath++; }
		if(rpath<r_end) rpath++; 	// rpath = "remaining/rpath"

	// handle k1
	// discard "//"
		if (k1==l_end) continue;

	// discard "./"
		if (k1+1==l_end&&*k1=='.') { l_end = k1; continue; }

	// "../" -> backup one directory
		if( k1+2==l_end && k1[0]=='.' && k1[1]=='.' )
		{
			for( l_end=k1-1; l_end>lpath&&l_end[-1]!='/'; ) { l_end--; }
			continue;
		}

	// assume directory if ENOENT already encountered:
	//	if (enoent) continue;

	// does path component exist?
		struct stat statdata;
		*l_end=0;
		lstat(lpath,&statdata);
		if (Error())
		{
	#ifdef MATCH_INVALID_UTF8_PATHS
			if (Error()==ENOENT)
			{
				k1[-1]=0;
				cstr k2 = FindBrokenUTF8File( k1>lpath+1?lpath:"/", k1 );
				k1[-1]='/';
				if (k2)
				{
					l_end = k1;
					while(*k2) { *l_end++ = *k2++; }
					ClearError();
					*l_end=0;
					lstat(lpath,&statdata);
				}
				else ForceError(ENOENT);
			}
			if (Error())
	#endif
			{
				if( Error()==ENOENT && rpath==r_end ) ClearError();	// no error if final path component not found
				break;
			}
		}

	// handle directory:
		if( S_ISDIR(statdata.st_mode) )
		{
			continue;
		}

	// handle link:
		if( S_ISLNK(statdata.st_mode) && (rpath<r_end || follow_symlink) )
		{
			if (--lc==0) { SetError(ELOOP); break; }
			int n = readlink( lpath, l_end, rpath-l_end-1 );
			if (n<0) { SetError(ENAMETOOLONG); break; }
			if (n==0) { l_end = k1; continue; }
			if (rpath<r_end) *--rpath='/';
			while(n>1&&l_end[n-1]=='/') n--;
			rpath -= n;
			memmove( rpath, l_end, n );
			l_end = *rpath=='/' ? lpath : k1;
			continue;
		}

	// handle regular file ((or pipe et.al.))
		if( rpath<r_end ) SetError(ENOTDIR);
		break;
	}


	if ( l_end <= lpath+1 ) { *lpath='/'; l_end = lpath+1; }
	else if ( l_end[-1]=='/' ) l_end--;

	path = SubStr(lpath,l_end);
	if (Error()) ForceError( Using("%s: %s",Quoted(path),ErrorStr()) );
	XXLogOut(" = \"%s\"",path);
	return path;
}


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



// 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 );
}
*/









