// <copyright>
// 
// Copyright (c) 1993-1995
// Institute for Information Processing and Computer Supported New Media (IICM),
// Graz University of Technology, Austria.
// 
// </copyright>

//<file>
//
// Name:       filestat.C
//
// Purpose:    Interface to function stat
//
// Created:    18 Nov 94    Gerald Pani
//
// Description:
//
//</file>

#include "filestat.h"
#include "environ.h"

#if defined(SUN) && HG_OSMaj == 4
extern "C" {
     extern uid_t geteuid();
     extern uid_t getegid();
}
#  endif

FileStat FileStat::fileStat_;

boolean FileStat::execute() const {
     if (loaded_) {
	  if (buf_.st_uid == geteuid()) {
	       if (buf_.st_mode & S_IXUSR) {
		    return true;
	       }
	  }
	  if (buf_.st_gid == getegid()) {
	       if (buf_.st_mode & S_IXGRP) {
		    return true;
	       }
	  }
	  if (buf_.st_mode & S_IXOTH) {
	       return true;
	  }
     }
     return false;
}

boolean FileStat::readable() const {
     if (loaded_) {
	  if (buf_.st_uid == geteuid()) {
	       if (buf_.st_mode & S_IRUSR) {
		    return true;
	       }
	  }
	  if (buf_.st_gid == getegid()) {
	       if (buf_.st_mode & S_IRGRP) {
		    return true;
	       }
	  }
	  if (buf_.st_mode & S_IROTH) {
	       return true;
	  }
     }
     return false;
}

boolean FileStat::writable() const {
     if (loaded_) {
	  if (buf_.st_uid == geteuid()) {
	       if (buf_.st_mode & S_IWUSR) {
		    return true;
	       }
	  }
	  if (buf_.st_gid == getegid()) {
	       if (buf_.st_mode & S_IWGRP) {
		    return true;
	       }
	  }
	  if (buf_.st_mode & S_IWOTH) {
	       return true;
	  }
     }
     return false;
}

boolean FileStat::which( const RString& name, RString& fullName) {
     RString pathList;
     if (!Environ::getEnv( "PATH", pathList)) {
	  cerr << "Environment variable PATH doesn't exist" << endl;
	  return false;
     }
     
     if (executable( name)) {
	  fullName = name;
	  return true;
     }

     RString dir;
     int ndx = 0;

     while (pathList.gWordChar( ndx, ':', dir)) {
	  RString file = dir + "/" + name;
	  if (executable( file)) {
	       fullName = file;
	       return true;
	  }
     }
     return false;
}

