#!/bin/bash -x
#############################################
## Asterisk MJ Auto Patch v1.0             ##     
## This automates the chan_sip patching    ##
## This repalces the need to use mjproxy   ##
## Written by Michael LaSalvia			   ##
## Original patch file by: DTM and Teddy_b ##
## Run as root and from with in /usr/src   ##
#############################################
## WARNING USE AT YOUR OWN RISK            ##
## If this helps help support us           ##
#############################################

#Variables
 aVER=`asterisk -rx "core show version" | cut -f2 -d" "`
 asVER="asterisk-$aVER"
 wVER=`which wget`
 pVER=`which patch`
#Check for needed tools
 if [ $wVER == /usr/bin/wget ]
	then
		echo "** wget is installed **"
	else
		echo "** yum not installed: Installing now... **"
		yum install wget -y
fi
if [ $pVER == /usr/bin/patch ]
	then
		echo "** patch is installed **"
	else
		echo "** patch not installed: Installing now... **"
		yum install patch -y
fi
# Download Asterisk SRC
cd /usr/src
wget http://downloads.asterisk.org/pub/telephony/asterisk/old-releases/$asVER.tar.gz
tar -zxvf $asVER.tar.gz
cd $asVER/channels
wget http://www.digitaloffensive.com/files/chan_sip_mj_patch.txt
#Backup original files, though not needed since we have the source		
		cp -p /usr/src/$asVER/channels/chan_sip.so /usr/src/$asVER/channels/chan_sip.so.bk
		cp -p /usr/src/$asVER/channels/chan_sip.c /usr/src/$asVER/channels/chan_sip.c.bk
#Patch the files and compile
		patch -l <chan_sip_mj_patch.txt
		cd /usr/src/$asVER
./configure & make all 2>&1|tee /tmp/make.all
# Install new chan_sip.so file
#Some assurance since /usr/sbin/asterisk -rx "stop gracefully" does not always work
/usr/sbin/asterisk -rx "stop gracefully" 
		OUT=$?
if [ $OUT == 0 ]
	then
		echo "** Asterisk stoped **"
	else 
		echo "** Asterisk still running: Killing NOW **"
		killall asterisk
fi
cp -p /usr/src/$asVER/channels/chan_sip.so /usr/lib/asterisk/modules/chan_sip.so
#Restart Asterisk
echo "** Restarting Asterisk: I suggest a system reboot. But we will just start it for you now **"
/usr/sbin/asterisk

