# ttasess-lib.pl
# Common functions 

# load_tta_emulses($temp_f)
# Returns an array of hashtable, each containing info about one webtop. Each hash
# will always contain the keys "alias" "name" "link" etc .
sub load_tta_emulses
{
# read the obj properties from file
   local(@ttasess, $_, %idx, $lnum, @lin);
 
	# start by reading from file List

	$lnum = 0;
	open(FILETTASESS, $temp_f);
	while(<FILETTASESS>) {
		 if (/\S/ && !/^[#\+\-]/ && $lnum gt 0 ) {
		        chomp($lin);
			@lin = split(/: /, $_, -1);
		        $lin[1]=~ s/"//g;
		        $is_space=chop($lin[1]);
                        if ( $is_space eq " " ) { chop($lin[1]); }
			push(@ttasess, { 'property' => $lin[0],
				    'value' => $lin[1],
				    'num' => scalar(@ttasess) });
			$idx{$lin[0]} = $ttasess[$#ttaobj];
			}
		$lnum++;
		}
	close(FILETTASESS);
    return @ttasess;
}

sub load_tta_sess_info
{
 $ttases_id= $config{'ttases_id'};
 $ttases_app= $config{'ttases_app'};
 $ttases_client=$config{'ttases_client'};
 $ttases_appserv=$config{'ttases_appserv'};
 $ttases_time=$config{'ttases_time'};
 $ttases_user=$config{'ttases_user'};
 $ttases_pe=$config{'ttases_pe'};
 $ttases_resume=$config{'ttases_resume'};
 $ttases_status=$config{'ttases_status'};
 $ttases_serveruser=$config{'ttases_serveruser'};
 $lnum = 0;
 $nlin = 0;
 foreach $lin (&load_tta_emulses()) {
       $to_include=false;
       if ( $lin->{'property'} eq $ttases_id ) {
          if ( $nlin > 0 ) { $lnum++; };
          $all_ttasess[$lnum]{'id'} =  $lin->{'value'};
       } 
       if ( $lin->{'property'} eq $ttases_app ) {
            $all_ttasess[$lnum]{'application'} = $lin->{'value'};
            $to_include=true;
       }
       if ( $lin->{'property'} eq $ttases_client ) {
            $all_ttasess[$lnum]{'client'} = $lin->{'value'};
            $to_include=true;
       }
       if ( $lin->{'property'} eq $ttases_appserv ) {
            $all_ttasess[$lnum]{'applicationServer'} = $lin->{'value'};
            $to_include=true;
       }
       if ( $lin->{'property'} eq $ttases_time ) {
            $all_ttasess[$lnum]{'startTime'} = $lin->{'value'};
       }
       if ( $lin->{'property'} eq $ttases_user ) {
            $all_ttasess[$lnum]{'user'} = $lin->{'value'};
            $to_include=true;
       }
       if ( $lin->{'property'} eq $ttases_pe ) {
            $all_ttasess[$lnum]{'pe_id'} = $lin->{'value'};
       }
       if ( $lin->{'property'} eq $ttases_resume ) {
            $all_ttasess[$lnum]{'resume'} = $lin->{'value'};
       }
       if ( $lin->{'property'} eq $ttases_status ) {
            $all_ttasess[$lnum]{'status'} = $lin->{'value'};
            $to_include=true;
       }
       if ( $lin->{'property'} eq $ttases_serveruser ) {
            $all_ttasess[$lnum]{'serverUser'} = $lin->{'value'};
            $to_include=true;
       }
       $nlin++;
       if ( $to_include eq true ) {
            $ncount=0;
            foreach $countsess (@count_sess) {
              if ( $countsess->{'name'} eq $lin->{'value'} ) {
                 $ncount=$countsess->{numses}+1;
                 $countsess->{numses}=$ncount;
                 last;
              }
            }
            if ( $ncount eq 0 ) {
                 push(@count_sess, { 'name' => $lin->{'value'},
                                     'obj' => $lin->{'property'} ,
                                     'objalias' => $lin->{'value'} ,
                                     'descrip' => $lin->{'value'} ,
                                     'alias' => "" ,
                                     'objgrpalias' => $lin->{'value'} ,
                                     'grpalias' => "" ,
                                     'alias' => $lin->{'value'} , 'numsess' => '1' });
            }
       }
 }
}

sub sum_grp_sess
{
    local ($lin,$ncount,%lista,$alias,$objdescrip);

    @lista=@count_sess;
    foreach $lin (@lista) {
            $ncount=0;
            foreach $countsess (@count_sess) {
              if ( $countsess->{'name'} eq $lin->{'objgrpalias'} && $lin->{'objgrpalias'} ne "" ) {
#print  "=".$countsess->{'objgrpalias'}."=eq=".$lin->{'objgrpalias'}."==\n";
                 $ncount=$countsess->{numsess}+1;
                 $countsess->{numsess}=$ncount;
                 last;
              }
            }
            $alias="";
            $objdescrip="";
            if ( $ncount eq 0  && $lin->{'objgrpalias'} ne "" ) {
                 $obj=$lin->{'obj'};
                 if ( $lin->{'obj'} eq "user" ) { $obj="ous"; }
                 elsif ( $lin->{'obj'} eq "app" ) { $obj="grpapps"; }
                 elsif ( $lin->{'obj'} eq "host" ) { $obj="grphosts"; }
                   @lista=eval("\&list_$obj");
                   foreach $elem (@lista) {
                       if ( $elem->{'obj'} eq $countsess->{'objgrpalias'} ) {
                            $objdescrip=$elem->{descrip};
                            if ( "$objdescrip" eq "" ) { $objdescrip = $elem->{name} };
                            $alias=$elem->{alias};
                            last;
                       }
                   }
                 push(@count_sess, { 'name' => $lin->{'objgrpalias'},
                                     'obj' => $obj ,
                                     'objalias' => $lin->{'objgrpalias'} ,
                                     'objgrpalias' => $lin->{'objgrpalias'} ,
                                     'alias' => $lin->{'objgrpalias'},
                                     'grpalias' => "",
                                     'descrip' => $objdescrip,
                                     'numsess' => '1' });
            }
   }
}

sub setcount_envsess
{
       foreach $countsess (@count_sess) {
             if ( $countsess->{'name'} eq $ttasess->{'user'} ) {
                 $countsess->{'descrip'}="$NameUser ($OuName)";
                 $countsess->{'obj'}="user";   
                 $countsess->{'objalias'}=$UserName;   
                 $countsess->{'alias'}=$NameUser;   
                 $countsess->{'objgrpalias'}=$OuName;   
                 $countsess->{'grpalias'}=$OuAlias;   
             }
             if ( $countsess->{'name'} eq $ttasess->{'application'} ) {
                 $countsess->{'descrip'}="$NameApp ($NameAppGrp)";
                 $countsess->{'obj'}="app";   
                 $countsess->{'objalias'}=$NameApp;   
                 $countsess->{'alias'}=$AppAlias;   
                 $countsess->{'objgrpalias'}=$NameAppGrp;   
                 $countsess->{'grpalias'}=$GrpAppAlias;   
             }
             if ( $countsess->{'name'} eq $ttasess->{'applicationServer'} ) {
                 $countsess->{'descrip'}="$NameHost ($NameHostGrp)";
                 $countsess->{'obj'}="host";   
                 $countsess->{'objalias'}=$NameHost;   
                 $countsess->{'alias'}=$HostAlias;   
                 $countsess->{'objgrpalias'}=$NameHostGrp;   
                 $countsess->{'grpalias'}=$GrpHostAlias;   
             }
       }
}
sub alias_envsess
{
    local ($item,$ensObj);

         $app=$NameApp;
         $AppAlias="";
         $GrpAppAlias="";
         $OuAlias="";
         $HostAlias="";
         $GrpHostAlias="";
         $DomainAlias="";

    $ensObj=$OuName;
    foreach $item (&list_ous()) {
         if ( $item->{'ens'} eq $ensObj ) {
            $OuAlias=$item->{'alias'};
            last;
         }
    }
    $ensObj="ou=".$NameApp.",".$NameAppGrp;
    foreach $item (&list_apps()) {
         if ( $item->{'ens'} eq $ensObj ) {
            $AppAlias=$item->{'alias'};
            $GrpAppAlias=$item->{'grpalias'};
            last;
         }
    }
    $ensObj="ou=".$NameHost.",".$NameHostGrp;
    foreach $item (&list_hosts()) {
         if ( $item->{'ens'} eq $ensObj ) {
            $HostAlias=$item->{'alias'};
            $GrpHostAlias=$item->{'grpalias'};
            last;
         }
    }
    if ( "$NameDomain" ne "" ) { $NameDomain=$config{'cache_domain'}; }
    $ensObj="ou=".$NameDomain;
    foreach $item (&list_domains()) {
         if ( $item->{'ens'} eq $ensObj ) {
              $DomainAlias=$item->{'alias'};
              last;
         }
    }

}

sub scan_envsess {
         $ens_base=$config{'ens_base'}.$config{'tta_base'};
	 $UserName=~s/$config{'tta_ldapUser'}//;
	 $UserName=~s/,$config{'ldap_base'}//;
	 $UserName=~s/$config{'ens_base'}//;
	 $AppName=~s/$ens_base\///;
	 $AppName=~s/$config{'ens_base'}//;
	 $HostName=~s/...\/_dns\///;
	 $HostName=~s/$ens_base\///;
         if ( $debug eq 2 ) { print DebugLog "\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 DebugLog "$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].$OuName;
	           }
              } else {
                   $lastOuName=$OuName;
                   if ( "$OuName" ne "" ) { $OuName=",".$OuName; }
		   $OuName="ou=".$UserPath[1].$OuName;
	      }
          }
          if ( "$userType" ne "LDAP" ) { 
                $NameUser=$UserPath[1]; 
                $OuName=$lastOuName;
          }
          if ( "$tta_username" eq "" ) { $tta_username=$NameUser; }
  	  if ( $debug eq 2 ) { print DebugLog "\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 DebugLog "$AppPath[0] -- $AppPath[1] \n"; }
          }
          $NameApp=$AppPath[1];
  	  if ( $debug eq 2 ) { print DebugLog "\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 DebugLog "$HostPath[0] -- $HostPath[1] \n"; }
          }
          if ( $HostPath[1].length eq 0 ) {
               $NameHost=$HostPath[0];
          } else {
               $NameHost=$HostPath[1];
          }
          if ( $NameHostGrp.length eq 0 ) {
               # 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 ...
               foreach $item (&list_hosts()) {
                       if ( $item->{'ipname'} eq $NameHost ) {
                          $Name_Host=$item->{'ens'};
                          $GrpHostAlias=$item->{'grpalias'};
                          last;
                       }
               }
               foreach $item (&list_grphosts()) {
                       if ( $item->{'alias'} eq $GrpHostAlias ) {
                          $NameHostGrp=$item->{'ens'};
                          last;
                       }
               }
               if ( $Name_Host ne "" ) { $NameHost=$Name_Host;  }

               # this was an idyllic situation where Apps and Hosts Trees are identicals 
               # $NameHostGrp=$NameAppGrp;
               # $NameHostGrp=~s/RIMA/servidores/g;
          }
  	  if ( $debug eq 2 ) { print DebugLog "\n";}
}

sub write_countsess 
{
           &lock_file($config{'cron_sessout_file'});
           open(COUNTSESSFILE, ">$config{'cron_sessout_file'}");
              foreach $countsess (@count_sess) { 
                        $lin_countsess=$countsess->{'alias'}."::".$countsess->{'name'}."::".$countsess->{'obj'}."::".$countsess->{'objalias'}."::".$countsess->{'grpalias'}."::".$countsess->{'num'}."::\n";
                        print FILEHOSTS "$lin_hosts";
                   }
                   print COUNTSESSFILE "$lin_countsess\n";
              }
           close (COUNTSESSFILE);
           $str=$text{'user_made'}." ->  CountSESS";
           &additional_log('count_sess', undef, $str);
           &webmin_log($config{'cron_sessout_file'}, undef, "update");
           &unlock_file($config{'cron_sessout_file'});
}
1;  # Return true
