#Script to post process and get VoLTE info
#Version 1.0 - Giri|giri@apple.com


#use strict;
#use warnings;

my $log_file = $ARGV[0];
my $csv_file = $log_file . '.csv';
my ($ip_addr, $reg_status, $rat, $signal_level);
my ($location_lat, $location_lng, $location_elevation,$location_address);
my ($call_setup_status, $call_maint_status, $ims_reg, $call_rat, $sms_status);
my ($rat_sms_before, $rat_sms_after,$sms_total_cnt);
my $logs_folder = "";
my @call_setup_fcnt;
my @call_drop_cnt; 
my @call_rat_lte;
my @sms_success_cnt;
my $ims_registration;
my $ims_reg;

$ip_addr = $rat = $reg_status = $signal_level = "";
$location_lat = $location_lng = $location_elevation = $location_address = "";

my $loop_start_flag = 0;
my $loop_done_flag = 0;
my $loop_id = 0;
# Needed for month conversion (lookup table)
my %mon2num = (JAN => 1,FEB=> 2,MAR=> 3,APR=> 4,MAY=> 5,JUN=> 6,JUL=> 7,AUG=> 8,SEP=> 9,OCT=> 10,NOV=> 11,DEC=> 12,);


sub reformat_timestamp{
    
    my $input_str = shift;
    # Extract timestamp fields separately to reconstruct
    my @time_split = ($input_str =~ m/^(\w+).*(\d\d).*(\d\d\d\d).*[,|at].*(\d+):(\d+):(\d+).*(\w+)/);
    my $umonth 	= $time_split[0];
    my $day 	= $time_split[1];
    my $year	= $time_split[2];
    my $hour	= $time_split[3];
    my $minute	= $time_split[4];
    my $second	= $time_split[5];
    my $noon 	= $time_split[6];
    
    # Get numeric value of month
    my $hash_ref=uc(substr($umonth, 0, 3));
    my $month = $mon2num{$hash_ref};
    # AM/PM check. If PM add + 12 to hour
    if ($noon =~m/PM/){
        $hour+=12;}
    
    my $time_new_format = $year."-".$month."-".$day." ".$hour.":".$minute.":".$second."."."000";
    return $time_new_format;
}


#2013-03-27 18:56:24.226
sub milliseconds_from_timestamp
{
	my $timestamp = shift(@_);
	my ($year, $month, $day, $hour, $minute, $second, $milliseconds) =
    $timestamp =~ m{([0-9]+)-([0-9]+)-([0-9]+) ([0-9]+):([0-9]+):([0-9]+)\.([0-9]+)};
	$year -= 1900;
	$month--;
	
	return ((timegm($second, $minute, $hour, $day, $month, $year) * 1000) + $milliseconds)
}


open(R_FILE,"<$log_file") or die("$log_file $!");

# Write fields to populate in to the database
print "VoLTE PPscript, v1.0\n";
my $APbuild = `cat $log_file | grep BuildVersion`;
$APbuild =~ s/BuildVersion:\s+//g;
print "AP Build," . $APbuild;

my $BBbuild = `cat $log_file | grep 'Firmware Version'`;
$BBbuild =~ s/Firmware Version:\s+//g;
print "BB Build," . $BBbuild;

print `cat $log_file | grep 'Carrier'`;
print `cat $log_file | grep 'Test date'`;
print `cat $log_file | grep 'Test duration'`;
print `cat $log_file | grep 'Tester email'`;
print `cat $log_file | grep 'Phone number'`;
print "\n,Connection Information,,Starting Location,,,IMS registration, MOC stats,, SRLTE mode, SMS stats,,,";
print "\nRun #,UE IP Addr,Signal Level,Approximate Address,Latitude,Longitude,";
print "IMS registered, MOC setup success,MOC maint success,SRLTE mode,";
print "SMS Before RAT, After RAT, Result,";
print "Logs Folder Name\n";
print "Test\n";

while(my $line = <R_FILE>){
	if($line =~ m/Connection Status #: (\d+)/){
		$loop_id = $1;
    $loop_start_flag = 1;
}

# Device Connection Status...
if($line =~ m/pdp_ip0.+\s+inet\s([\w\.]+)\s/){ $ip_addr = $1; }
if($line =~ m/en0:.+\sinet\s([\w+\.]*).+status:\sactive\s.+/){ $ip_addr = 'WiFi_' . $1; }

if($line =~ m/Camped RAT:\s+\[(\w+)]/){ $rat = $1; }

if($line =~ m/Raw Signal Strength:\s+\[(-?\w+\sdBm)]/){ $signal_level = $1; }
if($line =~ m/Current location is <([\+\-]\d+.\d+),([\+\-]\d+.\d+)>\s(\w+\.\w+)/){
    ($location_lat, $location_lng, $location_elevation) = ($1, $2, $3);
    $location_lat =~ s/\+//g;
    my $curl_cmd = "'https://maps.googleapis.com/maps/api/geocode/json?latlng=" . $location_lat . "," . $location_lng
    . "&sensor=false' | grep -m 1 formatted_address | sed -e 's/^[ \t\"]*formatted_address[ \"\:]*//g' | sed -e 's/\",//g'";
    $location_address = `curl -s $curl_cmd`;
    $location_address =~ s/[,\n]//g;
}
# Adding AGPS Location in Post Processing
if($line =~ m/AGPS Location: ([\+\-]\d+.\d+),([\+\-]\d+.\d+)/) {
    ($location_lat, $location_lng) = ($1,$2);
    $location_lat =~ s/\+//g;
    my $curl_cmd2 = "'https://maps.googleapis.com/maps/api/geocode/json?latlng=" . $location_lat . "," . $location_lng
    . "&sensor=false' | grep -m 1 formatted_address | sed -e 's/^[ \t\"]*formatted_address[ \"\:]*//g' | sed -e 's/\",//g'";
    $location_address = `curl -s $curl_cmd2`;
    $location_address =~ s/[,\n]//g;
}


#Check if UE is IMS registered prior to call
if($line =~ m/Carrier,\s(\w+)/) {
	$ims_reg = $1;
	if ($ims_reg =~ m/IMS/)
	{
		$ims_registration = "Registered";
	}
}

# MOC processing
if($line =~ m/CallStatusSending (\w+)/) {
    $call_setup_status = $1;
    if ($call_setup_status =~ m/Success/) {
        push (@call_setup_fcnt, 0);
    }
    if ($call_setup_status =~ m/Drop|Fail/) {
        push (@call_setup_fcnt, 1);
    }
}

if ($line =~ m/Voice Call attempted on RAT (\w+)/)
{
	$call_rat = $1;
	if ($call_rat =~m /1xLTE/)
	{
	 push (@call_rat_lte,0);
	}
	else
	{
	 push (@call_rat_lte,1);
	}
}

if($line =~ m/MO Call Status:\s(\w+)/) {
    $call_maint_status = $1;
    if ($call_maint_status =~ m/Success/) {
        push (@call_drop_cnt, 0);
    }
    if ($call_maint_status =~ m/Drop/) {
        push (@call_drop_cnt, 1);
    }
}


# SMS processing
if ($line =~ m/SMS attempt #: (\d+)/) {$sms_total_cnt = $1; }
if($line =~ m/Active RAT \(SMS before\):\s+(\w+)/) { $rat_sms_before = $1; }
if($line =~ m/Active RAT \(SMS after\):\s+(\w+)/)  { $rat_sms_after = $1; }
if($line =~ m/SMSSent\s(\w+)/) {
	$sms_status = $1;
	if ($sms_status =~ m/PASS/) {push (@sms_success_cnt,1);}
}


if($line =~ m/\/var\/wireless\/Library\/Logs\/CrashReporter\/(.+)/){
    $logs_folder = $1;
    $loop_done_flag = 1;
}

if($loop_done_flag == 1){
 	
    # Final Row with all the data
    my $conn_info   = $ip_addr . "," . $signal_level . "," . $location_address . "," . $location_lat . "," . $location_lng;
    my $moc_data    = $ims_registration. ",".$call_setup_status. "," .$call_maint_status. "," . $call_rat;
   	my $sms_info 	= $rat_sms_before . "," . $rat_sms_after . "," . $sms_status;
    print $loop_id . "," . $conn_info . "," . $moc_data. "," . $sms_info. ",". $logs_folder . "\n";
    
    # Cleaning up variables...
    $ip_addr = $rat = $reg_status = $signal_level = "";
    $location_lat = $location_lng = $location_elevation = $location_address = "NA";
    $call_maint_status = "";
    $logs_folder = "";
    
    $loop_start_flag = 0;
    $loop_done_flag = 0;
}
}

# Was the last run interrupted?
if($loop_done_flag == 0 and $loop_start_flag == 1) {
	# Final Row with all the data
	my $conn_info   = $ip_addr . "," . $reg_status . "," . $rat . "," . $signal_level . "," . $location_address . "," . $location_lat . "," . $location_lng;
    my $moc_data    = $ims_registration. ",".$call_setup_status. "," .$call_maint_status. "," . $call_rat;
   	my $sms_info 	= $rat_sms_before . "," . $rat_sms_after . "," . $sms_status;
    print $loop_id . "," . $conn_info . "," . $moc_data. "," . $sms_info. ",". $logs_folder . "\n";
}

print "\n\nSummary Stats";

if ($loop_id > $sms_total_cnt)
{
	print "\n\n,Total Runs," . $loop_id . ",WARNING: Last run might have been interrupted";
	
} else
{
	print "\n\n,Total Runs," . $loop_id;
}


if (scalar(@call_setup_fcnt) > 0) {
	my $sum = 0;
	$sum += $_ for(@call_setup_fcnt);
	print "\n\n,Call Setup failure percentage," . sprintf("%.2f", 100 * $sum / $loop_id) . ",%";
	print "\n,Total number of calls that failed setup," . sprintf("%.2f",$sum);
}

if (scalar(@call_drop_cnt) > 0) {
	my $sum = 0;
	$sum += $_ for(@call_drop_cnt);
	print "\n\n,Call drop percentage," . sprintf("%.2f", 100 * $sum / $loop_id) . ",%";
	print "\n,Total number of calls dropped," . sprintf("%.2f",$sum);
}

if (scalar(@call_rat_lte) > 0) {
	my $sum = 0;
	$sum += $_ for(@call_rat_lte);
	print "\n\n,Calls originated on LTE," . sprintf("%.2f", 100 * $sum / $loop_id) . ",%";
	print "\n,Total number of calls that were on L," . sprintf("%.2f",$sum);
}


if (scalar(@sms_success_cnt) >= 0) {
	my $sum = 0;
	$sum += $_ for(@sms_success_cnt);
	print "\n\n,SMS Success %," . sprintf("%.2f",100 * $sum / $sms_total_cnt) . ",%";
    
}

close R_FILE;



