#!/bin/bash

echo "Script started!"
# Find Asterisk'S PID
Asterisk_PID=$(sudo cat /var/run/asterisk/asterisk.pid)
# echo $Asterisk_PID
# Get asterisk uptime 
Asterisk_PID_Uptime=$((ps -p $Asterisk_PID -o etime=) | tr -d ':-')
# echo $Asterisk_PID_Uptime
# If Asterisk uptime is greater than 5 minutes, let's restart asterisk
# else Asterisk might have restarted after a crash and high number of processes in queue
# are normal in this case.

if  [ $Asterisk_PID_Uptime -gt 500 ]

then

	echo "Asterisk uptime is greater than 5 minutes"
	# Extract active locks from asterisk before executing gdb
	asterisk -x "core show locks" > /var/log/asterisk/saved_debug/core-show-locks.txt
	# Extract active channels from asterisk before executing gdb
	asterisk -x "core show channels" > /var/log/asterisk/saved_debug/Channel_list.txt
	# Extract process in queue
	asterisk -x 'core show taskprocessors' > /var/log/asterisk/saved_debug/Task_processors_list.txt

	# Execute gdb on asterisk PID to extract Backtraces
	gdb -ex "thread apply all bt" --batch /usr/sbin/asterisk $Asterisk_PID > /var/log/asterisk/saved_debug/backtrace-threads.txt

	# Copy log files to a new directory 
	cp /var/log/asterisk/full /var/log/asterisk/saved_debug
	cp /var/log/asterisk/messages /var/log/asterisk/saved_debug

	# Restart asterisk service because we have a possible deadlock in a production system
	# Do not forget to allow 'zabbix' user to restart asterisk without password in visudo
	# Add this line in visudo zabbix ALL=NOPASSWD: /etc/init.d/asterisk restart
	
	# Enable pjsip logger to capture packets 
	sudo asterisk -x "pjsip set logger on" > /dev/null 2>&1
	# Capture console output for 20 seconds to check if asterisk is receiving packets
	/usr/bin/timeout -s KILL 20s asterisk -rvvvv  > /var/log/asterisk/saved_debug/Console_output.txt
	# Restart asterisk	
	sudo /etc/init.d/asterisk restart
	echo "Restarting asterisk... "
 
	
else

	# We have processes in queue because Asterisk might have restarted after a crash
	echo "Processes are in queue asterisk just started... "

fi


echo 'script executed!'
