# 
# $Header: nshPreFileOpenChk.pl 14-apr-2005.12:17:53 ajere Exp $
#
# nshPreFileOpenChk.pl
# 
# Copyright (c) 2004, 2005, Oracle. All rights reserved.  
#
#    NAME
#      nshPreFileOpenChk.pl - Script to check file attributes prior to opening
#
#    DESCRIPTION
#      <short description of component this file declares/defines>
#
#    NOTES
#      <other useful comments, qualifications, etc.>
#
#    MODIFIED   (MM/DD/YY)
#    ajere       04/12/05 - Make file size limit configurable 
#    ajere       02/03/05 - Windows: Fix get parent directory 
#    ajere       12/07/04 - Change the file size limit 100 KB 
#    ajere       08/24/04 - Creation
# 

require "emd_common.pl";

#############################################
# performPreFileOpenChk()
# Perform pre-open file checks
#############################################
sub performPreFileOpenChk() {
  #Input params
  my $osCmd           = $ARGV[0];
  my $fileName        = $ARGV[1];
  my $fileSizeLimitKB = $ARGV[2];

  my $directory         = $fileName;
  my $preFileOpenChkOut = '';
  my $windowsOsCmd      = "cmd";
  my $unixOsCmd         = "/bin/sh";
  
  #Return flags
  my $dirWrite        = 'false';
  my $fileExists      = 'false';
  my $fileRead        = 'false';
  my $isFileDirectory = 'false';
  my $isTextFile      = 'false';
  my $fileWrite       = 'false';
  my $fileTooBig      = 'false';
  
  #Check if the file is a directory file
  if(-d $fileName) {
  	#print ("$fileName is a directory!\n") ;
  	$isFileDirectory = 'true';
  }

  #Get the parent directory
  if ($osCmd eq $windowsOsCmd) {
    #Windows
    if($fileName =~ /(.*\\)/) {
      $directory = $1;
    }
  } elsif ($osCmd eq $unixOsCmd) {
    #UNIX
    if ($fileName =~ m!(.*\/)!) {
    	$directory = $1;
    }
  }
  #print ("directory = $directory\n");	

  #Check if the parent directory has write permission
 	if ((-d $directory)&&(-w $directory)) {
 		#print ("$directory has write access.\n");	
 		$dirWrite = 'true';
 	}

  #Check if the file exists
  if (-e $fileName) {
  	#print "\n$fileName exists !\n";
  	$fileExists = 'true';
  }

  #Check if the file has read permission
  if (-r $fileName) {
  	#print ("$fileName has read access!\n") ;
  	$fileRead = 'true';
  }

  #Check if the file is a text file
  if (-T $fileName) {
  	#print ("$fileName is a text file.!\n") ;
  	$isTextFile = 'true';
  }

  #Check if the file has write permission
  if (-w $fileName) {
  	#print ("$fileName has write access!\n") ;
  	$fileWrite = 'true';
  }

  #Check if the file is > maximum limit
  if (($fileSizeLimitKB =~ /\d/) && ((-s $fileName) > $fileSizeLimitKB*1000)) {
  	#print ("$fileName is too big to fetch!\n") ;
  	$fileTooBig = 'true';
  }

 $preFileOpenChkOut =  $isFileDirectory.'|'.$dirWrite.'|'.$fileExists.'|'.$fileRead.'|'.$isTextFile.'|'.$fileWrite.'|'.$fileTooBig."\n";
 return $preFileOpenChkOut;
}

#For testing only
#my $preFileOpenChkOut = performPreFileOpenChk();
#print "$preFileOpenChkOut";
