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

//<file>
//
// Name:       lfilestat.C
//
// Purpose:    Interface to function lstat
//
// Created:    07 Jan 1997  Bruno Reisinger
//
// Description:
//
// $Id: lfilestat.C,v 1.2 1997/01/29 13:56:02 gorasche Exp $
//
//</file>
//
// $Log: lfilestat.C,v $
// Revision 1.2  1997/01/29 13:56:02  gorasche
// include for Windows sys/stat.h
//
// Revision 1.1  1997/01/07 10:18:10  breising
// Initial revision
//
//

#include <stdio.h>
#include <errno.h>
#include "lfilestat.h"
#include "environ.h"
#include <sys/stat.h>

const char* LFileStat::version1_1;

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

LFileStat LFileStat::fileStat_;

boolean LFileStat::load( const RString& name) {
   while (::lstat( name, &buf_) < 0) {
      if (errno != EINTR) {
	 if (errno == ENOENT) 
	    loaded_ = false;
	 else {
	    perror("LFileStat::load:lstat");
	    loaded_ = false;
	 }
	 return loaded_;
      }
   }
   loaded_ = true;
   return loaded_;
}

boolean LFileStat::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 LFileStat::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 LFileStat::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 LFileStat::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;
}

