#!/usr/local/bin/perl
# 
# $Header: dbDataFilePerm.pl 12-jan-2007.12:11:45 manosing Exp $
#
# dbDataFilePerm.pl
# 
# Copyright (c) 2004, 2006, Oracle. All rights reserved.  
#
#    NAME
#      dbDataFilePerm.pl - <one-line expansion of the name>
#
#    DESCRIPTION
#      <short description of component this file declares/defines>
#
#    NOTES
#      <other useful comments, qualifications, etc.>
#
#    MODIFIED   (MM/DD/YY)
#    manosing    01/12/07 - XbranchMerge manosing_lastpols from main
#    manosing    12/28/06 - flood control for windows policy
#    manosing    12/21/06 - adding check for  "0()" 
#    dsukhwal    05/20/05 - limit the number of rows 
#    dsukhwal    05/04/05 - handle win32 cases 
#    dsukhwal    02/15/05 - exceptional cases in file_perm usage 
#    dkjain      12/28/04 - Removed check_permission()
#    dkjain      10/31/04 - Fixed unable to connect
#    dkjain      10/08/04 - dkjain_esa_impl_init
#    dkjain      10/08/04 - Creation
# 
  require "emd_common.pl";
  require "semd_common.pl";
  require "$ENV{EMDROOT}/sysman/admin/scripts/db/esaDbUtils.pl";
  require "$ENV{EMDROOT}/sysman/admin/scripts/db/esaUtils.pl";

  my $maxCount;
  my $limit = 0 ;
  my %stdinArgs = get_stdinvars();
  my $username = $stdinArgs{"EM_TARGET_USERNAME"};
  my $password = $stdinArgs{"EM_TARGET_PASSWORD"};
  my $oracleHome = $ENV{EM_TARGET_ORACLE_HOME};
  my $address = $ENV{EM_TARGET_ADDRESS};
  my $role = $ENV{EM_TARGET_ROLE};
  my $mode = 0;
  
  if($^O eq "MSWin32"){
    $maxCount = $ENV{NDMAXCOUNT} ;
  }else{
    $maxCount = $ENV{DMAXCOUNT} ;
  }
  if($role =~ /SYSDBA/i)
  {
    $mode = 2;
  }
  elsif($role =~ /SYSOPER/i)
  {
    $mode = 4;
  }

  my $dsn = "dbi:Oracle:" ;
  my $property='oh_datafiles_perm'; #the property is nt_$property for mswin32.
  my $table = "dba_data_files";  
  my $value = "file_name";
  my $rowNum = 0 ;

  my $dbh = open_db_connection("dbi:Oracle:", "$username@".$address,$password,$mode); 
  my @dataFiles = getValue($dbh,$value,"", "",$table);
  close_db_connection($dbh);

  if($maxCount >= 0){
    splice(@dataFiles, $maxCount);
  }
  db_data_file_perm(@dataFiles);
  
  sub db_data_file_perm{
   my $fpath ;
   if($^O eq "linux"){
       my $retMode ;
       foreach $fpath (@_) {
        $retMode = file_perm($fpath); 
        if($retMode >= 0) { #file_perm returns -1 in case of failure
         $retMode = $retMode & 0777; 
         if(($retMode & 006)) { 
           #$permString = rwx_string($retMode);
           $fpath  = check_512char($fpath);
           printf "em_result=$property|%03o|$fpath\n",$retMode;
           $rowNum++;
         } 
        }
       }
   }
   elsif($^O eq "MSWin32"){
    foreach $fpath (@_){
        my $users = win32_file_perm($fpath);
        if($users == -1 || $users eq "0()") {next;}
        print "em_result=nt_$property|$users|$fpath\n";
    }
   }
  }
   
