# Library 
# ttacache-lib  
# STTA Rev. 1.3 Copyright (c) 2001-2004 Jesús Pérez Lorenzo  --- license GNU GPL 
# stta: (@#) 1.31051043346- [2004_01_29_102036]

# Read Config File
sub initialize () {
   if ( $debug gt 0 ) {
         @linlogfile = split(/\//, $tta_logfile);
         $logfile_ext=$linlogfile[$#linlogfile];
         $logfile_ext=~s/.log//g;
         $logfile_ext=~s/script//g;
         $CacheDebugFile=$config{cache_debuglog}.$logfile_ext.".log";
         open(CacheDebugLog, ">$CacheDebugFile");
   }
}

sub outData
{

    &get_data;
    if ( $debug gt 0 ) { &print_data(); };
#    print "global env \n";
   
    if ( $check_maxsess eq "true" ) {
         %countsess_reg=&list_countsess();
    }
    if ( $check_maxsess eq "true" &&  &checkMaxsess() ne 0 ) {
         print "set msg_access               \"$msg_nosess $obj\" \n";
         if ( $debug gt 0  ) { print CacheDebugLog "msg_access \"$msg_nosess $obj\" \n"; };
         return;
    }
    if ( $check_ticket eq "true"  && &checkTicket() ne 0 ) {
         print "set msg_access               \"$msg_noticket $obj\" \n";
         if ( $debug gt 0 ) { print CacheDebugLog "msg_access \"$msg_noticket $obj\" \n"; };
         if (  $tta3tier_doifendticket ne "" ) { &do_ifendticket() };
         return;
    }
    if ( "$WinAppServer" ne "" ) {
	    print "set uname               \"$tta3tier_login\" \n";
 	    print "set pword               \"$tta3tier_password\" \n";
 	    if ( $tta3tier_domain ne "" ) {
                  print "set env(TTA_Domain)           \"$tta3tier_domain\" \n";
            }
    } else {
	    print "set args(username)             \"$tta3tier_login\" \n";
 	    print "set args(password)             \"$tta3tier_password\" \n";
    }
    &out_data_cmd; 
}

sub out_data_cmd 
{
   if ( "$use_ttalogin_values" eq true ) {
         $login=$tta_username;
         $ttalogin=$tta_username;
         $password=$tta_password;
         $ttapassword=$tta_password;
 	 $TargetHost=$tta_host;
   }
            print "set msg_access               \"\" \n";
 	    print "set app(login)             \"$login\" \n";
 	    print "set app(password)             \"$password\" \n";
 	    print "set app(ttalogin)             \"$ttalogin\" \n";
 	    print "set app(password)             \"$ttapassword\" \n";
 	    print "set app(host)             \"$TargetHost\" \n";
            if ( $domain ne "" ) {
    	         print "set app(domain)             \"$domain\" \n";
            }
	    print "set appextra_cmd            \"";
            if ( "$extra_cmd" eq true ) { 
                eval ("print  \"$tta3tier_stringcmd\"") ; 
                if ( $debug eq 2 ) {
                     print CacheDebugLog "-------- APP LAUNCH VALUES -------------------\n";
                     eval ("print CacheDebugLog \"appextra_cmd - $tta3tier_stringcmd \n\"");
                }
            };
	    print "\"\n";
            if ( "$extra_expect" eq true ) {
                 for ( $i=1 ; $i< $numKeyLimit+1; $i++ ) {
                          $obj=eval("\$appkey$i");
#                          if ( "$obj" ne "" ) {
	                       print "set expe_appkey$i      \"";
                               eval ("print  \"$obj\"") ;
	                       print "\"\n";
                               if ( $debug eq 2 ) { eval ("print CacheDebugLog \"appkey$i -- $obj \n\"") };
#                          }
                 }
            }
            if ( $debug eq 2 && "$extra_cmd" eq true ) {
                  print CacheDebugLog "----------------------------------------------\n";
            }
}

sub out_empty_data
{
        $login="";$ttalogin="";$password="";$ttapassword="";$domain="";
        $appkey1="";$appkey2="";$appkey3="";$appkey4="";$appkey5="";$appkey6;
        $host=$NameHost;
        $extra_cmd=false;
        $tta3tier_stringcmd="";
        $extra_expect=false;

        &out_data_cmd; 
}

sub scan_env {
         if ( $debug eq 2 ) { print CacheDebugLog "\nScanning $UserName ....\n";}
   	 $lnumUser =0 ;
         # First LDAP user  and second TTA user
         $userType="LDAP";
         @linUserName = split(/,/, $UserName);
         if ("$linUserName[0]" eq "$UserName") { 
              $userType="TTA";
              @linUserName = split(/\//, $UserName);
         }
	 $OuName="";
	 foreach $obj (@linUserName) {
              @UserPath= split(/=/,$obj);
              $lnumUser++;
  	      if ( $debug eq 2 ) { print CacheDebugLog "$UserPath[0] -- $UserPath[1] \n"; }
              if ( "$userType" eq "LDAP" ) {
                   if ( $UserPath[0] eq "cn"  &&  $lnumUser eq 1 ) {
		        $NameUser=$UserPath[1];
                   } else {
                        if ( "$OuName" ne "" ) { $OuName=$OuName.","; }
		        $OuName.="ou=".$UserPath[1];
	           }
              } else {
                   $lastOuName=$OuName;
                   if ( "$OuName" ne "" ) { $OuName=$OuName.","; }
		   $OuName.="ou=".$UserPath[1];
	      }
          }
          if ( "$userType" ne "LDAP" ) { 
                $NameUser=$UserPath[1]; 
                $OuName=$lastOuName;
          }
          if ( "$tta_username" eq "" ) { $tta_username=$NameUser; }
  	  if ( $debug eq 2 ) { print CacheDebugLog "\nScanning $AppName ....\n";}
          $lnumApp = 0;
          @linAppName = split(/\//, $AppName);
          $NameAppGrp="";
	  foreach $obj (@linAppName) {
              @AppPath= split(/=/,$obj);
              if ( $lnumApp lt $#linAppName ) { 
                  if ( "$NameAppGrp" ne "" ) { $NameAppGrp=",".$NameAppGrp; }
	          $NameAppGrp="ou=".$AppPath[1].$NameAppGrp;
              }
              $lnumApp++;
  	      if ( $debug eq 2 ) { print CacheDebugLog "$AppPath[0] -- $AppPath[1] \n"; }
          }
          $NameApp=$AppPath[1];
  	  if ( $debug eq 2 ) { print CacheDebugLog "\nScanning $HostName ....\n";}
          $lnumHost = 0;
          @linHostName = split(/\//, $HostName);
          $NameHostGrp="";
	  foreach $obj (@linHostName) {
              @HostPath= split(/=/,$obj);
              if ( $lnumHost lt $#linHostName ) { 
                  if ( "$NameHostGrp" ne "" ) { $NameHostGrp=",".$NameHostGrp; }
	          $NameHostGrp=$HostPath[0]."=".$HostPath[1].$NameHostGrp;
              }
              $lnumHost++;
  	      if ( $debug eq 2 ) { print CacheDebugLog "$HostPath[0] -- $HostPath[1] \n"; }
          }
          if ( $HostPath[1].length eq 0 || $HostPath[1] eq "" ) {
               $NameHost=$HostPath[0];
          } else {
               $NameHost=$HostPath[1];
          }
          if ( $NameHostGrp eq "" ) {
               # TTA does not set equal TTA_HostName and TTA_ApplicationName  ENV
               # in TTA_HostName will have only a word with the "host-address"(ip orname)
               # From STTA vers. 1.2 host-address is in "list_host" file records
               # it is enforced to be unique ... so NameHostGrp and NameHost can be ...
               # Load by IP ...
               %h_hosts=&list_hosts(5);
               if ( $h_hosts{$NameHost}->{'ipname'} eq $NameHost ) {
                    $Name_Host=$h_hosts{$NameHost}->{'obj'};
                    $GrpHostAlias=$h_hosts{$NameHost}->{'grpalias'};
               }
               %h_hosts=&list_grphosts();
               if ( $h_hosts{$GrpHostAlias}->{'alias'} eq $GrpHostAlias ) {
                    $NameHostGrp=$h_hosts{$GrpHostAlias}->{'obj'};
               }
               if ( $Name_Host ne "" )  { $NameHost=$Name_Host;  }
 
               # there is a play in an idyllic situation ...
               # where Apps and Hosts Trees are identicals
               # $NameHostGrp=$NameAppGrp;
               # $NameHostGrp=~s/APPS/servers/g;  # by example
          }
  	  if ( $debug eq 2 ) { print CacheDebugLog "\n";}
}

sub get_data
{

   $tta3tier_domain = $entryObj{tta3tierdomain};
   $tta3tier_login = $entryObj{tta3tierlogin};
   &cipher_text ( "decode",$entryObj{tta3tierpassword}, \$tta3tier_password);
   # $tta3tier_password = $entryObj{tta3tierpassword};
   $tta3tier_stringcmd = $entryObj{tta3tierstringcmd};
   $tta3tier_title = $entryObj{tta3tiertitle};
   $tta3tier_oudn = $entryObj{tta3tieroudn};
   $tta3tier_appkey1 = $entryObj{tta3tierappkey1};
   $tta3tier_appkey2 = $entryObj{tta3tierappkey2};
   $tta3tier_appkey3 = $entryObj{tta3tierappkey3};
   $tta3tier_appkey4 = $entryObj{tta3tierappkey4};
   $tta3tier_appkey5 = $entryObj{tta3tierappkey5};
   $tta3tier_appkey6 = $entryObj{tta3tierappkey6};
   $tta3tier_maxsess = $entryObj{tta3tiermaxsess};
   $tta3tier_ticketstatus = $entryObj{tta3tierticketstatus};
   $tta3tier_ticketcounter = $entryObj{tta3tierticketcounter};
   $tta3tier_endticket = $entryObj{tta3tierendticket};
   $tta3tier_doifendticket = $entryObj{tta3tierdoifendticket};

  if ( $tta3tier_stringcmd ne "" ) {
       $extra_cmd=true;
       $login=$tta3tier_login;
       $password=$tta3tier_password;
       $ttalogin=$tta_username;
       $ttapassword=$tta_password;
       if ( $tta3tier_domain ne "" ) {
            $domain=$tta3tier_domain;
       }
       if ( $tta3tier_appkey1 ne "" ) { 
                $extra_expect=true;
   		$appkey1=$tta3tier_appkey1;
   		$appkey2=$tta3tier_appkey2;
   		$appkey3=$tta3tier_appkey3;
   		$appkey4=$tta3tier_appkey4;
   		$appkey5=$tta3tier_appkey5;
   		$appkey6=$tta3tier_appkey6;
       }
   }
}

sub print_data
{
   print CacheDebugLog "-------- LDAP CACHE VALUES -------------------\n";
   print CacheDebugLog "login	= $tta3tier_login\n";
   print CacheDebugLog "pasword	=$tta3tier_password\n";
   print CacheDebugLog "stringcmd	=$tta3tier_stringcmd\n";
   print CacheDebugLog "title	=$tta3tier_title\n";
   print CacheDebugLog "domain	=$tta3tier_domain\n";
   print CacheDebugLog "oudn	=$tta3tier_oudn\n";
   print CacheDebugLog "appkey1	=$tta3tier_appkey1\n";
   print CacheDebugLog "appkey1	=$tta3tier_appkey2\n";
   print CacheDebugLog "appkey1	=$tta3tier_appkey3\n";
   print CacheDebugLog "appkey1	=$tta3tier_appkey4\n";
   print CacheDebugLog "appkey1	=$tta3tier_appkey5\n";
   print CacheDebugLog "appkey1	=$tta3tier_appkey6\n";
   print CacheDebugLog "maxsess	=$tta3tier_maxsess\n";
   print CacheDebugLog "ticketstatus	=$tta3tier_ticketstatus\n";
   print CacheDebugLog "ticketcounter=$tta3tier_ticketcounter\n";
   print CacheDebugLog "endticket	=$tta3tier_endticket\n";
   print CacheDebugLog "doifendticket	=$tta3tier_doifendticket\n";
   print CacheDebugLog "-------- TTA LOGIN VALUES --------------------\n";
   print CacheDebugLog "tta_username	= $tta_username\n";
   print CacheDebugLog "tta_pasword	= $tta_password\n";
   print CacheDebugLog "tta_host	= $tta_host\n";
   print CacheDebugLog "----------------------------------------------\n";
   if ( "$WinAppServer" ne "" ) {  
       print CacheDebugLog "-------- Windows APP VALUES ---------------\n";
       print CacheDebugLog "uname	= $ttai3tier_username\n";
       print CacheDebugLog "pword	= $ttai3tier_password\n";
       print CacheDebugLog "TTA_Domain	= $ttai3tier_domain\n";
       print CacheDebugLog "----------------------------------------------\n";
   }
#   print CacheDebugLog "TTA_LOGFILE	= $tta_logfile\n";
#   print CacheDebugLog "logfile_ext	= $logfile_ext\n";
}

sub print_results
{
   print CacheDebugLog "----------- ENVIRONMENT VALUES ----------------\n";
   print CacheDebugLog "TTA_UserName=$ENV{'TTA_UserName'}\n"; 
   print CacheDebugLog "UserName=$UserName\n";
   print CacheDebugLog "TTA_ApplicationName=$ENV{'TTA_ApplicationName'}\n"; 
   print CacheDebugLog "AppName=$AppName\n";
   print CacheDebugLog "TTA_HostName=$ENV{'TTA_HostName'}\n"; 
   print CacheDebugLog "TTA_DomainName=$ENV{'TTA_DomainName'}\n"; 
   if ( "$WinAppServer" ne "" ) {  
     print CacheDebugLog "TTA_WindowsApplicationServer=	= $WinAppServer\n";
   }
   print CacheDebugLog "----------- SCANNED PARAMS --------------------\n";
   print CacheDebugLog " Usuario ($userType):       $NameUser\n";
   print CacheDebugLog " Organization:      $OuName\n";
   print CacheDebugLog " Aplicacion:       $NameApp \n";
   print CacheDebugLog " Grupo Aplicacion:    $NameAppGrp \n";
   print CacheDebugLog " Host:          $NameHost \n";
   print CacheDebugLog " Grupo Hosts:       $NameHostGrp \n";
   print CacheDebugLog " Domain:       $NameDomain \n";
   print CacheDebugLog "----------------------------------------------\n";
   print CacheDebugLog "TTA_CONNECTIONSERVICE: $ConnectionService \n";
}
sub endclose_debug
{
   if ( "$use_ttalogin_values" eq true ) {
        print CacheDebugLog "using TTA login Values\n";
   } else {
        print CacheDebugLog "using LDAP login Values\n";
   }
   print CacheDebugLog "userType        = $userType\n";
   print CacheDebugLog "----------------------------------------------\n";
   close (CacheDebugLog);
}


sub footCacheHere
{
   if ( $debug gt 0 ) { 
        print CacheDebugLog "----------------------------------------------\n";
        close (CacheDebugLog);
   }
}

sub footHere
{
   if ( $debug gt 0 ) {
        print CacheDebugLog "----------------------------------------------\n";
        close (CacheDebugLog);
   }
}

sub checkMaxsess
{
   if ( $has_cronsess ne "true" ) { return 0 }

   local $current_sess="";
   local $max_sess="";

   if ( $tta3tier_maxsess eq "0" ) { return -1 }
   %h_countsess=&list_countsess(3);
   $obj_target="";
   if ( "$obj" eq "users" ) { 
           $obj_target=$ENV{'TTA_UserName'}; 
   } elsif ( "$obj" eq "ous" ) { 
           $obj_target=$OuName;
   } elsif ( "$obj" eq "apps" ) { 
           $obj_target=$ENV{'TTA_ApplicationName'};
   } elsif ( "$obj" eq "grpapps" ) { 
           $obj_target=$NameAppGrp; 
   } elsif ( "$obj" eq "hosts" ) { 
           $obj_target=$NameHost; 
           $obj_target=~s/ou=/cn=/g;
   } elsif ( "$obj" eq "grphosts" ) { 
           $obj_target="$NameHostGrp";
           $obj_target=~s/ou=/cn=/g;
   } elsif ( "$obj" eq "domains" ) { 
           $obj_target="dc=$NameDomain";
   }
   if ( "$obj" eq "ous" || "$obj" eq "grpapps" || 
        "$obj" eq "hosts" || "$obj" eq "grphosts" || "$obj" eq "domains"){ 
             $obj_target=~s/,$//g;
             @line = split(/,/, $obj_target);
             $obj_target="";
             for ( $i=$#line; $i >= 0 ; $i-- ) {
                   if ( $i < $#line ) { $obj_target .= "/"; }
                   $obj_target.=$line[$i];
             }
            $obj_target="$config{'ens_base'}$config{'tta_base'}/$obj_target";
   }
   # print CacheDebugLog $h_countsess{$obj_target}->{'name'}." eq $obj_target \n";
   if  ( $h_countsess{$obj_target}->{'name'} eq $obj_target ) {
        $current_sess=$h_countsess{$obj_target}->{'numsess'};
        $max_sess=$h_countsess{$obj_target}->{'maxsess'};
   }
   if ( $debug gt 0 ) {
        print CacheDebugLog "----------------------------------------------\n";
        print CacheDebugLog "STTA session check: $obj_target  \n";
        print CacheDebugLog "counted sess  = $current_sess \n";
        print CacheDebugLog "cache object  = $tta3tier_maxsess \n";
        print CacheDebugLog "Def.  object  = $max_sess \n";
        print CacheDebugLog "----------------------------------------------\n";
   }
   if ( $current_sess ne "" ) {
        if ( $tta3tier_maxsess ne "" ) {
            if ( $tta3tier_maxsess le $current_sess ) { return -1 }
        } 
        if ( $max_sess ne "" ) {
            if ( $max_sess le $current_sess ) { return -1 }
        }   
   }
   return 0; 
}

sub checkTicket
{
        if ( $debug gt 0 ) {
             print CacheDebugLog "STTA ticket check: $tta3tier_ticketstatus  \n";
        }
        if ( $tta3tier_ticketstatus eq "no" ) { 
             if ( $debug gt 0 ) {
                print CacheDebugLog "----------------------------------------------\n";
             }
             return 0; 
        } elsif ( $tta3tier_ticketstatus eq "day" ) { 
             local $ahora=&set_now();
             local @line = split(/ /, $ahora);
             local $nowDay=$line[0];
             $nowDay=~s/-//g;
             if ( $debug gt 0 ) {
                print CacheDebugLog "nowDay     = $nowDay \n";
                print CacheDebugLog "endticket  = $tta3tier_endticket \n";
                print CacheDebugLog "----------------------------------------------\n";
            }
            if (substr($nowDay,4,4) gt substr($tta3tier_endticket,4,4) ) { return -1 }
            if (substr($nowDay,2,2) gt substr($tta3tier_endticket,2,2) ) { return -1 }
            if (substr($nowDay,0,2) gt substr($tta3tier_endticket,0,2) ) { return -1 }
        } elsif ( $tta3tier_ticketstatus eq "time" ) { 
             local $ahora=&set_now();
             local @line = split(/ /, $ahora);
             local $nowHour=$line[1];
             $nowHour=~s/://g;
             local $now_h=substr($nowHour,0,2);
             local $end_h=substr($tta3tier_endticket,0,2);
             local $now_m=substr($nowHour,2,2);
             local $end_m=substr($tta3tier_endticket,2,2);
             local $now_s=substr($nowHour,4,2);
             local $end_s=substr($tta3tier_endticket,4,2);
             local $now_tsec=($now_h*3600)+($now_m*60)+$now_s;
             local $end_tsec=($end_h*3600)+($end_m*60)+$end_s;
             if ( $debug gt 0 ) {
                print CacheDebugLog "nowHour    = $nowHour \n";
                print CacheDebugLog "endticket  = $tta3tier_endticket \n";
                print CacheDebugLog "now_sec    = $now_tsec \n";
                print CacheDebugLog "end_sec    = $end_tsec \n";
                print CacheDebugLog "----------------------------------------------\n";
             }
             if ( $now_tsec gt $end_tsec ) { return -1 };
        } elsif ( $tta3tier_ticketstatus eq "counter" ) { 
            if ( $debug gt 0 ) {
                print CacheDebugLog "endticket  = $tta3tier_endticket \n";
                print CacheDebugLog "ticketcounter = $tta3tier_ticketcounter \n";
                print CacheDebugLog "----------------------------------------------\n";
            }
             if ( $tta3tier_ticketcounter+1 gt $tta3tier_endticket ) { return -1 }
             $in{tta3tier_ticketcounter}=$tta3tier_ticketcounter+1;
             $dn=$dn_obj;
             $ldapcache_server=1;
             if ( &mod_obj($dn) eq 0 ) { 
                 if ( $config{ldapcache2_server}.length gt 0 ) {
                      $ldapcache_server=2;
                      &connect_cache ();
                      if ( &mod_obj($dn) ne  0 &&  $debug gt 0 ) { 
                          print CacheDebugLog "($dn):".$text{'replica_err'} ."-->".$line_conn."\n";
                          print CacheDebugLog "$text{'replica_msg'}\n";
                      }
                }
                if ( $debug gt 0 ) {
                     print CacheDebugLog "ticketcounter updated = $in{tta3tier_ticketcounter} \n";
                }
            }
        }
   
   return 0; 
}

sub do_ifendticket() 
{
      if ( $debug gt 0 ) {
           print CacheDebugLog "STTA doifendticket: $tta3tier_doifendticket  \n";
           print CacheDebugLog "----------------------------------------------\n";
      }
      if  ( $tta3tier_doifendticket eq "delwebtop" ) {
             $obj_target=$OuName;
             $obj_target=~s/,$//g;
             @line = split(/,/, $obj_target);
             $obj_target="";
             for ( $i=$#line; $i >= 0 ; $i-- ) {
                   if ( $i < $#line ) { $obj_target .= "/"; }
                   $obj_target.=$line[$i];
             }
            $ens_obj="$config{'ens_base'}$config{'tta_base'}/$obj_target/cn=$NameUser";
            $ens_obj=~s/,$//g;
            $temp_f = &tempname();
            $temp_f .= "scancache";
            $ens_link=$ENV{'TTA_ApplicationName'};
            open(TEMPF, ">$temp_f");
                print TEMPF " --name \"$ens_obj\" --link \"$ens_link\" \n";
            close(TEMPF);
            $type_cmd = "del_link";
            $tta_ok=true;
#           system("su -c \"tta object remove_link --file $temp_f\"");
            if ( &run_tta_cmd($type_cmd,$ens_obj,$temp_f) && $debug gt 0 ) {
                print CacheDebugLog "$tta3tier_doifendticket: $ens_link  \n";
            }
      } elsif  ( $tta3tier_doifendticket =~ /^run / ) {
           local $cmd=$tta3tier_doifendticket;
           $cmd=~ s/^run //g;
           &run_cmd($cmd);
      } elsif  ( $tta3tier_doifendticket =~ /^act / ) {

      } elsif  ( $tta3tier_doifendticket =~ /^system / ) {
           local $cmd=$tta3tier_doifendticket;
           $cmd=~ s/^system //g;
           system($cmd);
      }
}

1;  # Return true
