#!/bin/bash
#--------------------------------------------------------------------------------------------
# Accessibility script for testing following functions
# VoLTE/1X calls
# Version 1.0
# Author: Giri (giri@apple.com)
#------------------------------------------------------------------------------------------
testDuration=60
tester_email="dummy@apple.com"

while getopts 'f:a:e:h' OPTION;
do
case "$OPTION" in
a ) testDuration="$OPTARG";;
e ) tester_email="$OPTARG";;
f ) location_switch="$OPTARG";;
h ) echo "Usage: ./volte.sh [test_duration_in_minutes] [Email ID]"; exit 1;;
/?) echo "INVALID OPTIONS.\n"; exit 1;;
esac
done
shift $(($OPTIND - 1))


function log_enable ()
{

# Enable default logging
echo "Status: Enabling Baseband with Thumper logging"
/usr/local/bin/testCT -t CSILog enabled true
/usr/local/bin/testCT -t CSILog enableGlobalLogging true
/usr/local/bin/testCT -t EURCoreDump enabled 1
/usr/local/bin/testCT -t DIAG enabled true
/usr/local/bin/testCT -t CSILog history 512
/usr/local/bin/testCT -t DIAG history 8192
#Added internal mode
/usr/local/bin/testCT -t DIAG mode 0
# Additional changes
/usr/local/bin/testCT -t DIAG file_primary Default
/usr/local/bin/testCT -t DIAG file_secondary Thumper
/usr/local/bin/testCT -t DIAG enabled_during_sleep true
/usr/local/bin/mobilewifitool manager power 0


# For disabling iMessages
max_retry=2
retry_count=1
while [[ $retry_count -lt $max_retry ]]
do
echo "Status: Disabling iMessages. Attempt no: $retry_count"
result=`scripter -f /usr/local/etc/scripterUIA/general/ExecuteTest.js settingsTest_changeSingleSwitch "Messages" "iMessage" 0 2>&1|grep "report: Test"`
if [[ $result =~ .*PASS.* ]]
then
echo "Status: iMessage disable successful"
break
else
(( retry_count++ ))
if [[ $retry_count -eq 3 ]]
then
echo "***ERROR: FAILED TO DISABLE iMESSAGES***"
echo "DISABLE manually by going to Messages - iMessage - OFF"
fi
fi
done
}

function log_revert ()
{
# Enable default logging
echo "Status: Enabling Baseband & GPS logging"
/usr/local/bin/testCT -t CSILog enabled true
/usr/local/bin/testCT -t CSILog enableGlobalLogging true
/usr/local/bin/testCT -t EURCoreDump enabled 1
/usr/local/bin/testCT -t DIAG enabled true
/usr/local/bin/testCT -t CSILog history 512
/usr/local/bin/testCT -t DIAG history 128
# Additional changes
/usr/local/bin/testCT -t DIAG file_primary Default
/usr/local/bin/testCT -t DIAG file_secondary GPS
/usr/local/bin/testCT -t DIAG enabled_during_sleep true
/usr/local/bin/mobilewifitool manager power 1


# For Enabling iMessages
max_retry=2
retry_count=1
while [[ $retry_count -lt $max_retry ]]
do
echo "Status: Enabling iMessages. Attempt no: $retry_count"
result=`scripter -f /usr/local/etc/scripterUIA/general/ExecuteTest.js settingsTest_changeSingleSwitch "Messages" "iMessage" 1 2>&1|grep "report: Test"`
if [[ $result =~ .*PASS.* ]]
then
echo "Status: iMessage Enable successful"
break
else
(( retry_count++ ))
if [[ $retry_count -eq 3 ]]
then
echo "***ERROR: FAILED TO Enable iMESSAGES***"
echo "DISABLE manually by going to Messages - iMessage - ON"
fi
fi
done
}


# Function to format in mm-dd-yyyy-xxh_xxm_xxs
function format_date ()
{
 fdate=`date "+%m-%d-%Y-%Hh_%mm_%Ss"`
 echo $fdate
 }


# Function to get MS-ISDN number. Returns the phone number
function get_phone_number ()
{
	# Finds phone no between the square brackets [] and uses the same phone as destination for SMS and MMS
  	phone_number=`CoreTelephonyMonitor -q 2>&1 | grep 'Phone Number:' | sed -e 's/Phone Number://g' | tr -d "[]"`;
	echo $phone_number
}

# Function to get the current camped RAT
# Returns camped RAT
function get_active_rat ()
{
	rat=`testCT -b active 2>&1 | sed -e 's/.*kCTRegistrationRadioAccessTechnology//g' | tr -d "\n"`
	echo $rat
}

# Function to get the operator info
# Returns Carrier name
function get_carrier_info ()
{
	carrier_info=`CoreTelephonyMonitor -q 2>&1 | grep -m 1 'Operator:' | sed -e 's/Operator://g'|tr -d "[]"`
	echo $carrier_info
}

# Function to configure the following
# Disable sleep, cleanup old logs, configure log masks, get device details and output it to stdout file
function device_initialize ()
{
	nohup pmset noidle &
	
	# Cleaning previous logs...
	#rm -r /var/wireless/Library/Logs/CrashReporter/*
	rm *.out *.txt *.pcap
	
	# LOGGING CONFIGURATION ---> DONE SEPARATELY (NEW SCRIPT)
	echo "Script version, VoLTE 1.0" >>$stdout_file
	echo "SerialNumber,$serial_number" >>$stdout_file
	echo "UniqueDeviceID,"$(gestalt_query UniqueDeviceID 2>&1) >>$stdout_file

	sw_vers | grep BuildVersion >>$stdout_file
	CoreTelephonyMonitor -q 2>&1 | grep 'Firmware Version' | sed 's/:\s+//g' >>$stdout_file
	echo "Carrier," $(get_carrier_info) >>$stdout_file

	echo "Test date," $(format_date) >>$stdout_file
	echo "Test duration is, $testDuration seconds" >>$stdout_file 
	echo "TestSessionID, $test_start_time" >>$stdout_file
	echo "Phone number, $(get_phone_number)" >>$stdout_file
	echo "Tester email, $tester_email" >>$stdout_file
	echo "*****************************************************" >>$stdout_file
}

# Function to enable location services
function locmon_on ()
{
	echo "Enabling location services" >>$stdout_file
	nohup loctool nosleep &
	nohup locmon -y -2 2>locmon_output.txt &
}

# Random number generator for sleep function. Returns a value between min and max
function rand_generator ()
{
	# To generate random number between min and max

	min_val=10
	max_val=180
	rand_number=$((min_val+RANDOM%(max_val-min_val+1)))
	echo $rand_number
}

# Voice call test . Returns nothing
function MOC_test ()
{
 	echo "======================">>$stdout_file
	echo " MOC attempt #: $1" >>$stdout_file
	echo "======================">>$stdout_file
	#echo $(date +"%F %T") "Carrier," $(get_carrier_info) >>$stdout_file
	echo $(date +"%F %T") Call origination $(testCT -c 4255807887) >>$stdout_file
	echo $(date +"%F %T") Voice Call attempted on RAT $(get_active_rat) >>$stdout_file
	call_duration=$(rand_generator)
	echo $(date +"%F %T") " MO Call Duration is $call_duration">>$stdout_file
	
	sleep $call_duration
		if [[ $(testCT -x) == *active* ]]
		then 
		echo $(date +"%F %T") " MO Call Status: Success">>$stdout_file
		testCT -e >>$stdout_file
		else
		echo $(date +"%F %T") "MO Call Status: Drop">>$stdout_file
		fi
}

# SMS. Returns nothing
function SMS_test ()
{
    echo "======================">>$stdout_file
    echo " SMS attempt #: $1" >>$stdout_file
    echo "======================">>$stdout_file
    dest_number=$(get_phone_number)
    #echo "Phone number for SMS is $dest_number" >>$stdout_file
	echo "\n"$(date +"%F %T") "testCT Active RAT (SMS before):" $(get_active_rat) >>$stdout_file
	#echo $(date +"%F %T") SMS send/receive $(testCT -r $dest_number "Test SMS $1" "Test SMS $1") >>$stdout_file
	echo $(date +"%F %T") SMS send $(testCT -s $dest_number "Test SMS $1") >>$stdout_file
	echo "\n"$(date +"%F %T") "testCT Active RAT (SMS after):" $(get_active_rat) >>$stdout_file
}


# Stop TCPdump, dump BB logs, move logs to directory with iteration count
function cleanup ()
{
	echo "\n" $(date +"%F %T") "Iteration # $1 finished!\n" >>$stdout_file	
	echo $(date +"%F %T") "Stopping PCAP logging..." >>$stdout_file
	kill $tcpdump_pid
	echo $(date +"%F %T") "Dumping Baseband logs...">>$stdout_file
	killall -USR2 CommCenter
	echo $(date +"%F %T") "Locking screen..." >>$stdout_file
	interact lock	
	echo $(date +"%F %T") "Sleeping for 10 seconds..." >>$stdout_file
	sleep 10
	
	echo $(date +"%F %T") "Moving BB and PCAP logs..." >>$stdout_file	
	mv /var/wireless/Library/Logs/CrashReporter/Baseband /var/wireless/Library/Logs/CrashReporter/${test_start_time}_volte_$1
	mv PCAP_call_$1.pcap /var/wireless/Library/Logs/CrashReporter/${test_start_time}_volte_$1
	echo $(date +"%F %T") "Log files saved at: /var/wireless/Library/Logs/CrashReporter/${test_start_time}_volte_$1" >>$stdout_file	
		
}

function interupt_handle ()
{
echo $(date +"%F %T") "Process was killed or Interrupt was received ! " >> $stdout_file
echo $(date +"%F %T") "Cleanup Process Started" >> $stdout_file
mv *.txt /var/wireless/Library/Logs/CrashReporter/
/usr/bin/perl /private/var/mobile/Documents/iTester/Scripts/Shell/Telephony/LTECellSWPerf/Resources/pp_volte.pl /var/wireless/Library/Logs/CrashReporter/${test_start_time}_stdout.txt >/var/wireless/Library/Logs/CrashReporter/${test_start_time}_volte_ppresult.csv
echo $(date +"%F %T") "Finished Post Processing" >> $stdout_file
filename1=`cat /var/wireless/Library/Logs/CrashReporter/${test_start_time}_volte_ppresult.csv`
echo "Filename:"
echo "########################"
echo $filename1
echo "########################"
echo $(date +"%F %T") "Stopping PCAP logging..." >>$stdout_file
kill $tcpdump_pid
echo $(date +"%F %T") "Stopping RAT monitoring..." >>$stdout_file
kill $rat_pid
echo $(date +"%F %T") "LTE RAT count is:" $(grep -c LTE rat_monitor.txt) >>$stdout_file
echo $(date +"%F %T") "Total RAT count is:" $(grep -c RAT rat_monitor.txt) >>$stdout_file
echo $(date +"%F %T") "Unknown RAT count is:" $(grep -c Unknown rat_monitor.txt) >>$stdout_file
echo $(date +"%F %T") "Dumping Baseband logs...">>$stdout_file
killall -USR2 CommCenter
sleep 5
echo $(date +"%F %T") "Moving BB and PCAP logs..." >>$stdout_file
mv /var/wireless/Library/Logs/CrashReporter/Baseband /var/wireless/Library/Logs/CrashReporter/${test_start_time}_volte_last
mv *.pcap /var/wireless/Library/Logs/CrashReporter/${test_start_time}_volte_last
echo $(date +"%F %T") "Log files saved at: /var/wireless/Library/Logs/CrashReporter/${test_start_time}_volte_last" >>$stdout_file
echo "\n" $(date +"%F %T") "Cleanup Process Finished" >> $stdout_file
echo "\n" $(date +"%F %T") "$file1"
testCT -m "data_access@apple.com" "/var/wireless/Library/Logs/CrashReporter/${test_start_time}_volte_ppresult.csv" >>$stdout_file
testCT -m "$tester_email" "/var/wireless/Library/Logs/CrashReporter/${test_start_time}_volte_ppresult.csv"
echo $(date +"%F %T") "Sending email/MMS done..." >>$stdout_file
## Adding Return to Default Diag Logging
/usr/local/bin/testCT -t DIAG history 128
log_revert
killall -9 pmset loctool locmon pmset
exit 1;

}

#==================================================================================================
# 			------------- Main -----------------------------
#==================================================================================================
# Process test duration from command line, drive location, AP sleep requirements from command line
trap interupt_handle 15
# Process test duration from command line, drive location, AP sleep requirements from command line
# Process arguments in the order received
testDuration=$(($testDuration*60))
echo "Test duration is: $testDuration seconds"
echo "Tester email: $tester_email"
echo "Script is running now ................."


# Calculation of Test duration
currentTime=`date "+%s"`
testEndTime=$(($currentTime + $testDuration))
test_start_time=$(date +"%F_%H.%M")

# Creating a stdout_file with timestamp (unique)
stdout_file="${test_start_time}_stdout.txt"
run=1

# Get device details and clear old logs
device_initialize
log_enable
locmon_on

while [ "$currentTime" -lt "$testEndTime" ]
do	
	echo "==========================">>$stdout_file
	echo $(date +"%F %T") "Start of Iteration # $run" >>$stdout_file
	echo $(date +"%F %T") "Starting tcpdump on PDP_IP3" >>$stdout_file
	tcpdump -i pdp_ip3 -w PCAP_call_$run.pcap &
	tcpdump_pid=$!
	echo "Connection Status #: $run" >>$stdout_file
	echo "Cellular interface:" $(ifconfig pdp_ip0) >>$stdout_file
	echo "WiFi interface:" $(ifconfig en0)  >>$stdout_file
	CoreTelephonyMonitor -q 2>&1 | grep 'Raw Signal Strength' >>$stdout_file
    echo $(locmon 2>&1 | grep -E 'Location services enabled|Current location is')  >>$stdout_file
    
    MOC_test "$run";
	sleep 10
	
	SMS_test "$run";
    
	cleanup "$run";
	let run+=1
	
	currentTime=`date "+%s"`
done

# If this line is seen in the stdout, it indicates all runs have completed
echo $(date +"%F %T") "Test Script Completed $(($run-1)) Cycles\n" >>$stdout_file
# Will move stdout file to CrashReporter for easy syncing
mv *.txt /var/wireless/Library/Logs/CrashReporter/
sleep 10
/usr/bin/perl /private/var/mobile/Documents/iTester/Scripts/Shell/Telephony/LTECellSWPerf/Resources/pp_volte.pl /var/wireless/Library/Logs/CrashReporter/${test_start_time}_stdout.txt >/var/wireless/Library/Logs/CrashReporter/${test_start_time}_volte_ppresult.csv
testCT -m "data_access@apple.com" "/var/wireless/Library/Logs/CrashReporter/${test_start_time}_volte_ppresult.csv"
testCT -m "$tester_email" "/var/wireless/Library/Logs/CrashReporter/${test_start_time}_volte_ppresult.csv"
echo $(date +"%F %T") "Sending email/MMS done..." >>$stdout_file
## Adding Return to Default Diag Logging
/usr/local/bin/testCT -t DIAG history 128
log_revert
killall -9 pmset loctool locmon pmset
exit 1

