#!C:\perl\bin
################################
#       EDIREX2 subs 
#################################

#################################  
#     GET DATUM
#################################

sub getdatum
{
#
# Vytvor datum a cas jako jedinečnou identifuikaci okamziku cinnsoti 
# 
 my $microseconds = 10000;
usleep ( $microseconds);
my ($sekund,$dsec)=(0,0);
 ($sekund,$dsec)=gettimeofday;
my ($sec,$min,$hour,$mday,$mond,$year,$wday,$yday,$isdst) = localtime($sekund);
$year += 1900; # millennium proof
$mond += 1;     # perl has mon from 0..11; this makes 1..12
$min=sprintf("%.2d",$min);
$mond=sprintf("%.2d",$mond);
$sec=sprintf("%.2d",$sec);
$dsec=($dsec / 1000.0);
$dsec=sprintf("%3d",$dsec);
$mday=sprintf("%.2d",$mday);
$hour=sprintf("%.2d",$hour);
 $datum = "$year$mond$mday\-$hour\:$min\:$sec";
 $rok = "$year$mond$mday";
  $cas = substr($year,2,2)."$mond$mday$hour$min$sec$dsec";
  $cas =~tr/ /0/;
}
# end of soubrutine get datum 
#
;
#################################  
#     READ_params
#################################
sub read_params
{
 my  ($paroms,$parvalue);
 $paramfile="edirex.cfg";

 if (!(open(PARAMDATA, "<$paramfile"))) {
   print "!!! $datum Nemohu otevrit konfiguracni soubor: $paramfile !!!\n"; 
   exit;
 }
 $EDIREX_HOME=$ENV{EDIREX_HOME};
 while ($parameter = <PARAMDATA>){
   $parameter=~ s/^ *//g;
   ($parameter)=split(/\#/,$parameter);
   if($parameter eq '') { next;};
   chomp($parameter);
   $parameter=~s/ *$//g;
   ($paroms, $parvalue) = split(/\=/,$parameter);
   if(!defined($parvalue)) { $parvalue=''; }
   $parvalue=~ s/^ *//g;
   $paroms=~s/ *$//g;
   $parvalue=~ s/\$EDIREX_HOME/$EDIREX_HOME/g;
   $param{$paroms}=$parvalue; 
 }
 close PARAMDATA;
}
# end of  READ PARAMS
#################################  
#     init_param
#################################
sub Vypis_hlavicku
{ 
  print "*********************************************\n";
  print "*     EDIREX       ver: $VERZE\n";
  print "*     TELEDIN      tel: ++420 603433625\n";
  print "*********************************************\n"; 
};
#################################  
#     Test_parametru
#################################

sub Test_parametru() {
  if( ! open(AUDIT,">> $param{'edirex_log_dir'}/audit.log")) {
    print "Nemohu otevrit AUDIT LOG $param{'edirex_log_dir'}/audit.log pro zapis, koncim!\n";
    return 1;
  }
  print  AUDIT "\n";
  print  AUDIT "********************************************\n";
  print  AUDIT "*     EDIREX      ver: $VERZE\n";
  print  AUDIT "********************************************\n";
  chdir "$EDIREX_HOME";
  $param{'privatni_klic'}=".ssh/id_rsa";
  if( -e "id_rsa") { $param{'privatni_klic'}="id_rsa"; }
  if(defined($ARGV[0])) { 
    if($ARGV[0] eq "i"){
      $IOmode=1;
    } elsif($ARGV[0] eq "o"){
      $IOmode=2;
    } elsif(($ARGV[0] eq "io") or ($ARGV[0] eq "oi")){
      $IOmode=3;
    } else {
      print "Prvni parametr musi byt i, o nebo io!\n";
      return 1;
    }
  } else {
    print "Prvni parametr musi byt i, o nebo io!\n";
    return 1;
  }

my $i=1;
  while(defined($ARGV[$i])){
    if($ARGV[$i] eq "test"){
      &Hlaska("! TEST: Program EDIREX se pripoji na testovaci schranku !!!");
      $param{'edirex_user'}="testuser";
      $param{'NumRetryConn'}=0;
    }
    if($ARGV[$i] eq "testmsg"){
      $Chyba="TESTMSG: Program EDIREX zasila testovaci zpravu.";
      if ($param{'SendErrorEmail'} ne 1) { &Hlaska("! Neni nastaven parametr SendErrorEmail=1 !!"); return 1; }
      &error_log;
      return 1;
    }
    if(($ARGV[$i] eq "type") && defined($ARGV[$i+1])){
      @DownloadOnlyType=split(/\,/,$ARGV[$i+1]);
      &Hlaska("! Zadano stahovani pouze techto typu: @DownloadOnlyType !");
    }
    $i++;
  }

  if( -e "$param{'edirex_user'}_rsa" ) { $param{'privatni_klic'}="$param{'edirex_user'}_rsa"; }
  if( !-d $param{'edirex_outbound'}){
    &error_log2("! Direktorar $param{'edirex_outbound'} neexistuje, koncim !");
    return 1;
  }
  if( !-d $param{'edirex_inbound'}){
    &error_log2("! Direktorar $param{'edirex_inbound'} neexistuje, koncim !");
    return 1;
  }
  if( !-d $param{'edirex_inarchiv'}){
    if( !-d "$EDIREX_HOME/inarchiv") { mkdir("$EDIREX_HOME/inarchiv"); }
    if( -d "$EDIREX_HOME/inarchiv") {
      &error_log2("InArchiv $param{'edirex_inarchiv'} neexistuje, pouziji $EDIREX_HOME/inarchiv !");
      $param{'edirex_inarchiv'} = "$EDIREX_HOME/inarchiv";
    } else {
      &error_log2("! Direktorar $param{'edirex_inarchiv'} neexistuje, koncim !");
      return 1;
    }
  }
  if( !-d $param{'edirex_outarchiv'}){
    if( !-d "$EDIREX_HOME/outarchiv") { mkdir("$EDIREX_HOME/outarchiv"); }
    if( -d "$EDIREX_HOME/outarchiv") {
      &error_log2("OutArchiv $param{'edirex_outarchiv'} neexistuje, pouziji $EDIREX_HOME/outarchiv !");
      $param{'edirex_outarchiv'} = "$EDIREX_HOME/outarchiv";
    } else {
      &error_log2("! Direktorar $param{'edirex_outarchiv'} neexistuje, koncim !");
      return 1;
    }
  }
  if( !-d $param{'edirex_tmp_dir'}){
    if( !-d "$EDIREX_HOME/tmp") { mkdir("$EDIREX_HOME/tmp"); }
    if( -d "$EDIREX_HOME/tmp") {
      $param{'edirex_tmp_dir'} = "$EDIREX_HOME/tmp";
    } else {
      &error_log2("! Direktorar $param{'edirex_tmp_dir'} neexistuje, koncim !");
      return 1;
    }
  }
  $param{'edirex_in_dir'}="$param{'edirex_tmp_dir'}\\in";
  $param{'edirex_out_dir'}="$param{'edirex_tmp_dir'}\\out";
  if( !-d $param{'edirex_in_dir'}){
    if( !-d "$param{'edirex_tmp_dir'}/in") { mkdir("$param{'edirex_tmp_dir'}/in"); }
    if( -d "$param{'edirex_tmp_dir'}/in") {
      $param{'edirex_in_dir'} = "$param{'edirex_tmp_dir'}/in";
    } else {
      &error_log2("! Direktorar $param{'edirex_in_dir'} neexistuje, koncim !");
      return 1;
    }
  }
  if( !-d $param{'edirex_out_dir'}){
    if( !-d "$param{'edirex_tmp_dir'}/out") { mkdir("$param{'edirex_tmp_dir'}/out"); }
    if( -d "$param{'edirex_tmp_dir'}/out") {
      $param{'edirex_out_dir'} = "$param{'edirex_tmp_dir'}/out";
    } else {
      &error_log2("! Direktorar $param{'edirex_out_dir'} neexistuje, koncim !");
      return 1;
    }
  }
  if($param{'edirex_user'} eq "NOBODY" ){
    &error_log2("Nebyl nastaven spravny uzivatel v souboru EDIREX.cfg, koncim !");
    return 1;
  }
  if( !-e "$EDIREX_HOME/$param{'privatni_klic'}" ){
    &error_log2("! Nebyl nalezen privatni klic pro autorizaci na CCF serveru, koncim !");
    return 1;
  }
  if(!&TestMista()){
    $Chyba="! Malo mista na disku (<2MB), koncim !";
    &error_log;
    return 1;
  }
  if(defined(Win32::Mutex->open("edirex"))){      # Sleduj, zda nebezi minuly EDIREX
    if(defined($param{'Kill_old'}) and ($param{'Kill_old'} eq '1')) { &KillOld(); }  # Kdyz povoleno, kill
    else { 
      &error_log2("! Bezi jina instance EDIREXu, koncim !");
      return 1;
    }
  }
  $mut = Win32::Mutex->new(0,"edirex");
  if( -e "$param{'edirex_log_dir'}/inmsg.log" ){
    rename("$param{'edirex_log_dir'}/inmsg.log","$param{'edirex_log_dir'}/inmsg.tmp");
  }
  if( -e "$param{'edirex_log_dir'}/outmsg.log" ){
    rename("$param{'edirex_log_dir'}/outmsg.log","$param{'edirex_log_dir'}/outmsg.tmp");
  }
  return 0;
}
#################################  

sub Hlaska(){

  print AUDIT "* $datum @_\n";
  print       "* $datum @_\n";
}
#################################  

sub ZavriAUDIT(){

  close(AUDIT);
  if( -e "$param{'edirex_log_dir'}/inmsg.tmp" ){
    rename("$param{'edirex_log_dir'}/inmsg.tmp","$param{'edirex_log_dir'}/inmsg.log");
  }
  if( -e "$param{'edirex_log_dir'}/outmsg.tmp" ){
    rename("$param{'edirex_log_dir'}/outmsg.tmp","$param{'edirex_log_dir'}/outmsg.log");
  }
  $mut->Release();
}

#################################

sub TestMista(){
  if($param{'TestovatMisto'} ne 1) { return(1); } 
my($vycteno,$volnemisto,$volnemistomb)='';
  open3( 'WRITE','READ','ERROR', "dir /-C");
  while($vycteno = readline ('READ')) {
    if($vycteno=~/bytes free/) {
      ($volnemisto) = $vycteno =~ /.*\s+(\d+) bytes free/;
      last;
    }
    if($vycteno=~/ch bajt/) {
      ($volnemisto) = $vycteno =~ /.*ch bajt.: (.+)/;
      $volnemisto=~s/ //g;
      last;
    } 
  } 
  if(!defined($volnemisto)) { return(1); }   # Nevim, neplasim
  if ($param{'edirex_biolit'} >= 1){ &Hlaska("Volne misto: $volnemisto byte"); }
  if($volnemisto eq '') { return(1); }  # Nevim, neplasim
  $volnemistomb=substr($volnemisto,0,-6);
  if($volnemistomb > 3) { return(1); }  # Dost mista (v MB)
  else { return(0); }                   # Malo mista
}

#################################

sub TestMista_puv(){
  if (!open(TESTFREE, "> $param{'edirex_out_dir'}/testspace.txt")) { 
    return(0);
  }
  seek(TESTFREE,2000000,0);
  print(TESTFREE "end");
  close(TESTFREE);
  my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks)=stat("$param{'edirex_out_dir'}/testspace.txt");
  unlink("$param{'edirex_out_dir'}/testspace.txt");
  if($size == 2000003) {
    return(1);     # OK
  } else {
    return(0);     # Malo mista
  }
}

#################################

sub KillOld(){
my @Tlist=();
my $j;
my $vycteno;
  open3( 'WRITE','READ','ERROR', "tlist");
  while(1){
    $vycteno = readline ('READ');
    if(!defined($vycteno)) { last; }
    if(($vycteno=~/edirexperl/) or ($vycteno=~/edirexstck/)) {
      $j=substr($vycteno,0,5);  # Vyrizni cislo procesu
      $j=~s/\D//g;        # ponech jen cislice
      if($j ne $$) {push(@Tlist,$j); }
    }
  }
  if ($#Tlist > -1) {
    &Hlaska("! Kill: @Tlist");
    foreach $j (@Tlist) { kill(9,$j); }
  }
}

#################################  
#
#
#
#################################  
1;

 