#! /usr/bin/perl -w
use strict;
use warnings;
use POSIX;

use Digest::MD5;
use Crypt::Rijndael;

my $http_user="Username"; 
my $http_passwd="Password";
my $http_file_1="http://switzernet.com/folders/100716-php-asterisk";
my $http_file_2="http://unappel.ch/folders/100716-php-asterisk";
#my $Path_Wget="/usr/bin/wget";
my $Path_Wget="/home/usr/bin/wget";

sub md5sum{
  my $file = shift;
  my $digest = "";
  eval{
    open(FILE, $file) or die "[ERROR] md5sum: Can't find file $file\n";
    my $ctx = Digest::MD5->new;
    $ctx->addfile(*FILE);
    $digest = $ctx->hexdigest;
    close(FILE);
  };
  if($@){
    print $@;
    return "";
  }
  return $digest;
}

sub AlertMail{
 my $text = shift; 
 print "$text\n";
 my $syscom = '/bin/echo '.$text.' | /home/usr/bin/mailx -s \'Atrerisk-Perl: Update List Error \' alerts@unappel.ch';
 system $syscom;
 return $?;
}

sub GetKey{
my $cle="2345678";
open(FileKey,"/root/100105-asterisk-list/KeyAstr") || AlertMail ("Error opening file KeyAstr") ;
$cle =$_  while(<FileKey>);
$cle =~ s/^\s+//;
$cle =~ s/\s+$//;
close (FileKey);
return $cle;
}

####################################   Concurrence Detection   ####################################

system "/bin/date +\"%F %T\"";

my $max_exec=3;
my $i_exec=0;
my $fileN = "/root/100105-asterisk-list/permit";
my $comsys;
my $Reply;

for ($i_exec=0;$i_exec<$max_exec;$i_exec++)
   {
   $comsys="$Path_Wget -q --output-document='$fileN' --http-user=$http_user --http-passwd=$http_passwd  $http_file_1/CreatFile.php";
   system $comsys;
   if($?)
      {
      AlertMail "warning in the command '$comsys'\nError number:$?\n";
      $comsys="$Path_Wget -q --output-document='$fileN' --http-user=$http_user --http-passwd=$http_passwd  $http_file_2/CreatFile.php";
      system $comsys;
      if($?)
         {
         AlertMail "Error in the command '$comsys'\nError number:$?\n";
         exit 0;
         }
      }
   open(Permit,$fileN) || AlertMail ("Error opening file $fileN") ;
   $Reply="";
   $Reply.=$_ while (<Permit>) ;
   chomp($Reply);
   print "$i_exec: Reply $Reply\n";
   last if ($Reply eq "200 Ok");
   my $slp = 20 + ceil((90* rand ()));
   print "$i_exec: Sleep $slp s\n";
   sleep ($slp);
   }

if ($Reply ne "200 Ok")
	{
	AlertMail "Error in creating files for download $i_exec: Reply $Reply";
	exit 0;
	}

####################################   Liste Accounts   ####################################

$fileN = "/root/100105-asterisk-list/Asterisk-Accounts.txt";
my $fileC = "/root/100105-asterisk-list/Asterisk-Accounts.crypt";
my $fileO = "/etc/asterisk/db-friends.conf";

$comsys="$Path_Wget -q -N  --output-document='$fileN'  --http-user=$http_user --http-passwd=$http_passwd $http_file_1/file/Asterisk-Accounts.txt";

my $fg=0;
my $key = GetKey() ;
system $comsys;
if($?)
{
   AlertMail "warning in the command '$comsys'\nError number:$?\n";
   $comsys="$Path_Wget -q -N --output-document='$fileN' --http-user=$http_user --http-passwd=$http_passwd  $http_file_2/file/Asterisk-Accounts.txt";
   system $comsys;
   if($?)
       {
           AlertMail "Error in the command '$comsys'\nError number:$?\n";
	   exit 0;
       }
}

open(FileCrypt,$fileN) || AlertMail ("Error opening file $fileN") ;
my $Lign;
my $OutPut;
$Lign.=$_ while (<FileCrypt>) ;
my @res_split_Acc=split('</TR>', $Lign);
my $cipher = Crypt::Rijndael->new($key, Crypt::Rijndael::MODE_ECB() );
$cipher->set_iv($key);
#print("\nTotal ligne: ".scalar(@res_split_Acc));
my $CusSkip=0;
my $CusDecr=0;
my $ErrDecr=0;
for (my $i=0;$i<scalar(@res_split_Acc);$i++)
{
my @Td=split('</TD>', $res_split_Acc[$i]);
if (!(length($Td[0])%16)&&!(length($Td[1])%16))
{
$Td[0]=substr($cipher->decrypt($Td[0]), 0, 11);
$Td[1]=substr($cipher->decrypt($Td[1]), 0, 32);
if ($Td[0] =~ m/^[0-9]{11}$/ && $Td[1] =~ m/[a-z0-9]{32}/)
	{
	$CusDecr++;	
	$OutPut .= "[".$Td[0]."](phone)\nmd5secret=".$Td[1]."\n\n";
	}
else
	{
	$ErrDecr++;
	AlertMail "Decryption error: Result inconsistent with the value of Regexp in line ($i) phone=".$Td[0].", md5=".$Td[1]." !";
	}
}
else
{
$CusSkip++;
print("Customer in ligne ($i) skipped :length(Td[0])=".length($Td[0])." : length(Td[1])=".length($Td[1])."\n");
}
}
print("Total Customer skipped = $CusSkip\n");
print("Total Customer decrypted = $CusDecr\n");
print("Total Error in Decryption account file = $ErrDecr\n");
open (FH, ">$fileC") || AlertMail ("Error opening file $fileC") ;
print FH $OutPut;
close (FH);
close (FileCrypt);
if ($CusSkip)
	{
	print ("Send Mail to alert\@unappel.ch");
	AlertMail ("-Total Customer skipped = $CusSkip. -Total Customer decrypted = $CusDecr.") ;
	}

my $md5C =  md5sum($fileC);
my $md5O =  md5sum($fileO);

AlertMail "Error calculates MD5 file ".$fileC."\n" unless($md5C ne "");
AlertMail "Error calculates MD5 file ".$fileO."\n" unless($md5O ne "");

unless ($md5O eq $md5C)
	{
	system "/bin/cp $fileC $fileO";
	AlertMail "Error in the command 'cp $fileC $fileO'\nError number:$?\n" if($?);
	
	system "/bin/chown --change asterisk:asterisk $fileO";
	AlertMail "Error in the command 'chown --change asterisk:asterisk $fileO'\nError number:$?\n" if($?);
	$fg=1;
	print "md5 decrypted Accounts file is different to md5 of existing file\n";
	}
else
	{
	print "md5 decrypted Accounts file is equal to md5 of existing file\n";
	}

####################################   Liste Nodes   ####################################

my $DN=0;
$fileN = "/root/100105-asterisk-list/Asterisk-Nodes.txt";
$fileC = "/etc/asterisk/db-peers.conf";
$comsys="$Path_Wget -q -N --output-document='$fileN' --http-user=$http_user --http-passwd=$http_passwd  $http_file_1/file/Asterisk-Nodes.txt";
system $comsys;
if($?)
{
   AlertMail "warning in the command '$comsys'\nError number:$?\n";
   $comsys="$Path_Wget -q -N --output-document='$fileN' --http-user=$http_user --http-passwd=$http_passwd  $http_file_2/file/Asterisk-Nodes.txt";
   system $comsys;
   if($?)
       {
           AlertMail "Error in the command '$comsys'\nError number:$?\n";
	   exit 0;
       }
}

my $md5N =  md5sum($fileN);
$md5C =  md5sum($fileC);

AlertMail "Error calculates MD5 file ".$fileN."\n" unless($md5N ne "");
AlertMail "Error calculates MD5 file ".$fileC."\n" unless($md5C ne "");

unless($md5N eq $md5C)
	{
	system "/bin/cp $fileN $fileC";
	AlertMail "Error in the command 'cp $fileN $fileC'\nError number:$?\n" if($?);

	system "/bin/chown --change asterisk:asterisk $fileC";
	AlertMail "Error in the command 'chown --change asterisk:asterisk $fileC'\nError number:$?\n" if($?);
	$DN=1;
	$fg=1;
        print "md5 decrypted Node file is different to md5 of existing file\n";
        }
else
        {
        print "md5 decrypted Node file is equal to md5 of existing file\n";
        }


####################################   Liste Customer-Ip   ####################################

$fileN = "/root/100105-asterisk-list/Asterisk-customer-ip.txt";
$fileC = "/etc/asterisk/db-customer-ip.conf";
$comsys="$Path_Wget -q -N --output-document='$fileN' --http-user=$http_user --http-passwd=$http_passwd  $http_file_1/file/Asterisk-customer-ip.txt";
system $comsys;
if($?)
{
   AlertMail "warning in the command '$comsys'\nError number:$?\n";
   $comsys="$Path_Wget -q -N --output-document='$fileN' --http-user=$http_user --http-passwd=$http_passwd  $http_file_2/file/Asterisk-customer-ip.txt";
   system $comsys;
   if($?)
       {
           AlertMail "Error in the command '$comsys'\nError number:$?\n";
           exit 0;
       }
}

$md5N =  md5sum($fileN);
$md5C =  md5sum($fileC);

AlertMail "Error calculates MD5 file ".$fileN."\n" unless($md5N ne "");
AlertMail "Error calculates MD5 file ".$fileC."\n" unless($md5C ne "");

unless($md5N eq $md5C){
	system "/bin/cp $fileN $fileC";
	AlertMail "Error in the command 'cp $fileN $fileC'\nError number:$?\n" if($?);

	system "/bin/chown --change asterisk:asterisk $fileC";
	AlertMail "Error in the command 'chown --change asterisk:asterisk $fileC'\nError number:$?\n" if($?);

	$fg=1;
        print "md5 decrypted IP customers file is different to md5 of existing file\n";
        }
else
        {
        print "md5 decrypted IP customers file is equal to md5 of existing file\n";
        }


####################################   Liste Deny-Node   ####################################
if ($DN)
{
$fileC = "/etc/asterisk/db-peers.conf";
$fileN = "/etc/asterisk/db-deny-node.conf";
my $host;
my $ligne;
my $OutDN='';
open FICHIER,"< $fileC" || AlertMail ("Error opening file $fileC") ;
while ($ligne = <FICHIER>){
if(($host)=$ligne=~ /^host=(.+)/)
	{
	chomp($host);
	$OutDN .="deny=$host\n";
	}
}
close FICHIER;
open (FHDN, ">$fileN") || AlertMail ("Error opening file $fileN") ;
print FHDN $OutDN;
close (FHDN);
system "/bin/chown --change asterisk:asterisk $fileN";
AlertMail "Error in the command 'chown --change asterisk:asterisk $fileN'\nError number:$?\n" if($?);
}

####################################   Reload Asterisk   ####################################

if ($fg)
{
print "Reloading Asterisk \n";
system "/etc/init.d/asterisk reload";
AlertMail "Error in the command '/etc/init.d/asterisk reload'\nError number:$?\n" if($?);
}
else
{
print "Reloading Asterisk is not necessary\n";
}
print "-----------------------------------------------------------------------------------------------------------------\n\n";

