# ttasess-lib.pl
# Common functions 

sub load_tta_sess_info
{
 local $lnum=0;
 local $nlin=0;

 $ttases_id= $text{'ttases_id'};
 $ttases_app= $text{'ttases_app'};
 $ttases_client=$text{'ttases_client'};
 $ttases_appserv=$text{'ttases_appserv'};
 $ttases_time=$text{'ttases_time'};
 $ttases_user=$text{'ttases_user'};
 $ttases_pe=$text{'ttases_pe'};
 $ttases_resume=$text{'ttases_resume'};
 $ttases_status=$text{'ttases_status'};
 $ttases_serveruser=$text{'ttases_serveruser'};
 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  && $is_reload eq true ) {
            $ncount=0;
            $name_lin=$lin->{'value'};
            if ( $h_countsess{$name_lin}->{'name'} eq $lin->{'value'} ) {
                 $ncount=$h_countsess{$name_lin}->{numsess}+1;
                 $h_countsess{$name_lin}->{numsess}=$ncount;
            } else {
                 $h_countsess{$name_lin} = {
                                     'name' => $lin->{'value'},
                                     'obj' => $lin->{'property'} ,
                                     'objalias' => $lin->{'value'} ,
                                     'objgrpalias' => "" ,
                                     'descrip' => $lin->{'value'} ,
                                     'alias' => $lin->{'value'} ,
                                     'maxsess' => "",
                                     'grpalias' => "",
                                     'numsess' => '1'
                                   };
            }
       }
 }
}

sub sum_grp_sess
{
    local ($lin,$item,$ncount,$objectdescrip,$alias,$obj_maxsess,$objgrpalias);
    local %h_list=%h_countsess;

    foreach $lin (keys (%h_list)) {
            $ncount=0;
            $objgrpalias= $h_list{$lin}->{'objgrpalias'};
            if ( $h_countsess{$objgrpalias}->{'name'} eq $objgrpalias  &&
                 $h_list{$lin}->{'objgrpalias'} ne "" ) {
                 $ncount=$h_countsess{$objgrpalias}->{numsess};
                 $ncount++;
                 $h_countsess{$objgrpalias}->{'numsess'}=$ncount;
                 next;
            }
            $objectdescrip="";
            $obj_maxsess="";
            $alias= $h_list{$lin}->{'alias'};
            if ( $ncount eq 0  && $h_list{$lin}->{'objgrpalias'} ne "" ) {
#                print "<tr><td> $lin -- $h_countsess{$objgrpalias}->{'name'} - $ncount-$h_list{$lin}->{'objgrpalias'}</td></tr>\n"; 
                 $obj= $h_list{$lin}->{'obj'};
                 $grpalias= $h_list{$lin}->{'grpalias'};
                 if (  $h_list{$lin}->{'obj'} eq "user" ) { 
                      $obj="ous";
                      %h_listobj=&list_ous();
                 } elsif (  $h_list{$lin}->{'obj'} eq "app" ) { 
                      $obj="grpapps";
                      %h_listobj=&list_grpapps();
                 } elsif (  $h_list{$lin}->{'obj'} eq "host" ) {
                      $obj="grphosts";
                      %h_listobj=&list_grphosts();
                 } 
                 $alias=$grpalias; 
                 if ( $h_listobj{$grpalias}->{'alias'} eq $grpalias ) {
                      $obj_maxsess = $h_listobj{$grpalias}->{'maxsess'};
                      $objdescrip = $h_listobj{$grpalias}->{'descrip'};
                      if ( $objdescrip eq "" ) {
                            $objdescrip = $h_listobj{$grpalias}->{'name'};
                      };
                 }
                 if ( $objdescrip eq "" ) {
                       $objdescrip = $h_list{$grpalias}->{'descrip'};
                 };
                 $h_countsess{$objgrpalias} = {
                                     'name' =>  $h_list{$lin}->{'objgrpalias'},
                                     'obj' => $obj ,
                                     'objalias' =>  $h_list{$lin}->{'objgrpalias'} ,
                                     'objgrpalias' =>  $h_list{$lin}->{'objgrpalias'} ,
                                     'descrip' => $objdescrip ,
                                     'alias' => $alias,
                                     'maxsess' => $obj_maxsess,
                                     'grpalias' =>  $h_list{$lin}->{'grpalias'},
                                     'numsess' => '1'
                                   };
            }
   }
   # clean-up objgrp counters ...
   foreach $lin (keys (%h_countsess)) {
       if ( $h_countsess{$lin}->{'objalias'} eq $h_countsess{$lin}->{'objgrpalias'} &&
            $h_countsess{$lin}->{'objgrpalias'} ne "" ) {
                $h_countsess{$lin}->{grpalias}="";
                $h_countsess{$lin}->{objgrpalias}="";
       }
   }
   # Add Totals ...
     $alias="TOTAL";
     $objdescrip="TOTAL";
     $h_countsess{$alias} = {
                         'name' => $alias,
                         'obj' => $alias ,
                         'objalias' => $alias ,
                         'objgrpalias' => "",
                         'descrip' => $objdescrip ,
                         'alias' => $alias,
                         'maxsess' => "",
                         'grpalias' => "",
                         'numsess' => $#all_ttasess+1
                         };
}

sub setcount_envsess
{
       foreach $lin (keys (%h_countsess)) {
             if ( $h_countsess{$lin}->{'name'} eq $ttasess->{'user'} ) {
                 $h_countsess{$lin}->{'descrip'}="$NameUser ($OuName)";
                 $h_countsess{$lin}->{'obj'}="user";
                 $h_countsess{$lin}->{'objalias'}="cn=".$NameUser;
                 $h_countsess{$lin}->{'alias'}=$NameUser;
                 $h_countsess{$lin}->{'objgrpalias'}=$OuName;
                 $h_countsess{$lin}->{'maxsess'}="";
                 # Fix for unknown groups in defs lists  ( Administrator/o=Tarantella ...)
                 if ( $OuAlias eq "" ) { $h_countsess{$lin}->{'objgrpalias'}="" };
                 $h_countsess{$lin}->{'grpalias'}=$OuAlias;
             }
             if ( $h_countsess{$lin}->{'name'} eq $ttasess->{'application'} ) {
                 $h_countsess{$lin}->{'descrip'}="$NameApp ($NameAppGrp)";
                 $h_countsess{$lin}->{'obj'}="app";
                 $h_countsess{$lin}->{'objalias'}="ou=".$NameApp;
                 $h_countsess{$lin}->{'alias'}=$AppAlias;
                 $h_countsess{$lin}->{'maxsess'}=$AppMaxsess;
                 $h_countsess{$lin}->{'objgrpalias'}=$NameAppGrp;
                 $h_countsess{$lin}->{'grpalias'}=$GrpAppAlias;
             }
             if ( $h_countsess{$lin}->{'name'} eq $ttasess->{'applicationServer'} ) {
                 $h_countsess{$lin}->{'descrip'}="$NameHost ($NameHostGrp)";
                 $h_countsess{$lin}->{'obj'}="host";
                 $h_countsess{$lin}->{'objalias'}="ou=".$NameHost;
                 $h_countsess{$lin}->{'alias'}=$HostAlias;
                 $h_countsess{$lin}->{'maxsess'}=$HostMaxsess;
                 $h_countsess{$lin}->{'objgrpalias'}=$NameHostGrp;
                 $h_countsess{$lin}->{'grpalias'}=$GrpHostAlias;
             }
       }
}
sub alias_envsess
{
    local ($ensObj, %h_lista);

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

    $ensObj=$OuName;
    %h_lista=&list_ous(2);
    $OuAlias=$h_lista{$ensObj}->{'alias'};
    $OuMaxsess=$h_lista{$ensObj}->{'maxsess'};

    $ensObj="ou=".$NameApp.",".$NameAppGrp;
    %h_lista=&list_apps(3);
    $AppAlias=$h_lista{$ensObj}->{'alias'};
    $AppMaxsess=$h_lista{$ensObj}->{'maxsess'};
    $GrpAppAlias=$h_lista{$ensObj}->{'grpalias'};

    %h_lista=&list_hosts(3);
    $ensObj="ou=".$NameHost.",".$NameHostGrp;
    $HostAlias=$h_lista{$ensObj}->{'alias'};
    $HostMaxsess=$h_lista{$ensObj}->{'maxsess'};
    $GrpHostAlias=$h_lista{$ensObj}->{'grpalias'};
    if ( "$NameDomain" ne "" ) { $NameDomain=$config{'cache_domain'}; }
    $ensObj="ou=".$NameDomain;
    %h_lista=&list_domains(2);
    $DomainAlias=$h_lista{$ensObj}->{'alias'};
    $DomainMaxsess=$h_lista{$ensObj}->{'maxsess'};

}

sub scan_envsess {

   local (%h_hosts);

         $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 ...

               # Load by IP ...
               %h_hosts=&list_hosts(5);  
               if ( $h_hosts{$NameHost}->{'ipname'} eq $NameHost ) {
                    $Name_Host=$h_hosts{$NameHost}->{'ens'};
                    $GrpHostAlias=$h_hosts{$NameHost}->{'grpalias'};
               }
               %h_hosts=&list_grphosts();  
               if ( $h_hosts{$GrpHostAlias}->{'alias'} eq $GrpHostAlias ) {
                    $NameHostGrp=$h_hosts{$GrpHostAlias}->{'ens'};
               }
               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 DebugLog "\n";}
}

sub write_countsess 
{
    local ($lin,$lin_countsess);

           # Clean file first to get changes in Webmin Log !!!
           open(COUNTSESSFILE, ">$config{'countsessout_file'}");
                print COUNTSESSFILE "\n";
           close (COUNTSESSFILE);
           &lock_file($config{'countsessout_file'});
           open(COUNTSESSFILE, ">$config{'countsessout_file'}");
              print COUNTSESSFILE "#datetime: $ahora\n";
              foreach $lin (keys (%h_countsess)) {
                      if ( $lin ne "" ) {
                          $lin_countsess=$h_countsess{$lin}->{'objalias'}."::".
                                     $h_countsess{$lin}->{'numsess'}."::".
                                     $h_countsess{$lin}->{'descrip'}."::".
                                     $h_countsess{$lin}->{'name'}."::".
                                     $h_countsess{$lin}->{'alias'}."::".
                                     $h_countsess{$lin}->{'maxsess'}."::".
                                     $h_countsess{$lin}->{'objgrpalias'}."::".
                                     $h_countsess{$lin}->{'grpalias'}."::".
                                     $h_countsess{$lin}->{'obj'}."::";
                          print COUNTSESSFILE "$lin_countsess\n";
                     }
              }
           close (COUNTSESSFILE);
           &unlock_file($config{'countsessout_file'});
           $str=$text{'user_made'}." CountSESS";
           &additional_log('tta_sess.cgi', "ttasess", $str);
           &webmin_log($config{'countsessout_file'}, "ttasess", "update");
}

# To load TTA session Tables 
# if "has_cronsess" and "tta_sessout_file"  it will try to use stored info 
# $is_reload force to reload in case of true
# $counter_time & $counter_date are checked to match upon defined $config{sessout_timeout}
# $config{'tta_sessout_file'} & $config{'countsessout_file'} are read, clean or write 
# %h_countsess for counters and @tta_sess order ($sort_on) from @all_ttasess are set
# There are many Globals in this module ...
# CGI calling this function should pay attention to:
# $is_reload (true|false) as default
# $sort_op ( "pe_id"; "application"; "user"; "startTime"; "resume"; "status";
#             "applicationServer"; "client"; "serverUser"; "user"; )
# should use;
# $counter_time, $ttasess_time    %h_countsess  @tta_sess order on $sort_on @all_ttasess
sub ttasess_tables
{
    local($lnum,$ahora_str,$counter_time_str,$limit,$str,$lin);

    if ( "$ahora" eq "" ) { $ahora=&set_now(); }

    if ( $config{has_cronsess} eq "true" && $config{'tta_sessout_file'} ne "" && $is_reload ne true ) {
         $ahora_str=set_datetime_str($ahora);
         $counter_time="";
         %h_countsess=&list_countsess();
         $counter_time_str=set_datetime_str($counter_time);
#         $counter_times=get_datetime_str($counter_time_str);
         $limit=$config{sessout_timeout};

         $temp_f=$config{'tta_sessout_file'}; 
         if ( "$counter_time" eq "" ) {
              $is_reload=true;
         } else {
              $is_reload=false;
              # Just in case reset to every hour as default !!
              if ($limit < 1 || $limit > 14 ) { $limit=10 };
              if (substr($counter_time_str,0,$limit) ne substr($ahora_str,0,$limit) ) { 
                 $is_reload=true;
              }
         }
    }
    if ( $is_reload eq true ) {
         $type_cmd="emulatorsession";
         &run_tta_cmd($type_cmd);
         # $temp_f="/tmp/emu-tta2"; # for debugging to avoid run_tta_cmd !! uncomment also unlinlk($temp_f)
         if ( $config{has_cronsess} eq "true" && $config{'tta_sessout_file'} ne "" ) {
              # No locking ... &unlock diff cmd clean-up and crash this file contents
              # &lock_file($config{'tta_sessout_file'});
              open(TTASESSFILE, ">$config{'tta_sessout_file'}");
                   print TTASESSFILE "#datetime: $ahora\n";
                   open(TEMPF, "$temp_f");
                           while(<TEMPF>) { print TTASESSFILE "$_"; }
                   close(TEMPF);
             close (TTASESSFILE);
             # Just in case as chop function in loading has problems with chars lost ...
             #  $str=`cat $temp_f >> $config{'tta_sessout_file'}`;
             unlink($temp_f);
             $str=$text{'user_made'}." TTA SESS List";
             # No locking ... &unlock diff cmd clean-up and crash this file contents
             # &unlock_file($config{'tta_sessout_file'});
             &additional_log('tta_sess.cgi', "ttasess", $str);
             &webmin_log($config{'tta_sessout_file'}, "ttasess", "update");
             $temp_f=$config{'tta_sessout_file'};
        }
    }
    # this is only to get date 
    &load_tta_emulses("getdate");  
    if ( $is_reload ne true && "$counter_time" ne "$ttasess_time" ) {

         unlink($config{'tta_sessout_file'});
         system("rm -f $config{'tta_sessout_file'} ");
         &additional_log('tta_sess.cgi', "ttasess"," $ttasess_time - $counter_time");
         &webmin_log($config{'tta_sessout_file'}, "ttasess", "delete");

         unlink($config{'countsessout_file'});
         system("rm -f $config{'countsessout_file'} 2>/dev/null") ;
         &additional_log('tta_sess.cgi', "ttasess"," $ttasess_time - $counter_time");
         &webmin_log($config{'countsessout_file'}, "ttasess", "delete");

         $err_msg=$text{sessdiff_err};
         return -2;
    }
    &load_tta_sess_info();
    if ( $config{has_cronsess} ne "true" && $is_reload eq true ) {
#         system("rm $temp_f 2>dev/null");
         unlink($temp_f);
    }
    if ($#all_ttasess < 0) { $err_msg=$text{nosess_err}; return -1; }

    if ( !$sort_on ) { $sort_on="user"};
    @ttasess = sort {$a->{$sort_on} cmp $b->{$sort_on}} @all_ttasess;
    $lnum=0;
    foreach $ttasess (@ttasess) {
       $UserName=$ttasess->{'user'};
       $AppName=$ttasess->{'application'};
       $HostName=$ttasess->{'applicationServer'};
       &scan_envsess();
       &alias_envsess();
       $ttasess->{'nameUser'}=$NameUser;
       $ttasess->{'nameOu'}=$OuName;
       $ttasess->{'nameApp'}=$NameApp;
       $ttasess->{'nameAppGrp'}=$NameAppGrp;
       $ttasess->{'nameHost'}=$NameHost;
       $ttasess->{'nameHostGrp'}=$NameHostGrp;
       if ( $is_reload eq true ) { &setcount_envsess(); }
       if ( $debug gt 1 ) { &print_emulses(); }
       $lnum++;
    }

    if ( %h_countsess) {
       if ( $is_reload eq true ) { &sum_grp_sess();};
       $lnum=0;
       if ( $debug gt 1 ) {
            foreach $lin (keys (%h_countsess)) { 
               $lnum++;
               $objdescrip=$h_countsess{$lin}->{'descrip'}; 
               $objdescrip=~s/ou=//g;     
               $objdescrip=~s/cn=//g;     
               &print_countses($lnum,$lin);
            }
       }
    }
    if ( $config{has_cronsess} eq "true" && $config{'countsessout_file'} ne "" ) {
         if ( $is_reload eq true ) { &write_countsess(); }
    }
    return 0;
}   
1;  # Return true
