#!/bin/bash

echo " ViciBox Asterisk 11 changeover script"
echo
echo "  This will change the installed Asterisk version from Asterisk 13 to"
echo "  Asterisk 11 for compatibility with older installs. You will need to have"
echo "  Internet connectivity for this to work. This should be done prior to"
echo "  installing ViciDial on this server."
echo
echo -n "  Do you want to change over to Asterisk 11? (N/y) : "
read PROMPT

if [ "${PROMPT,,}" == "y" ]; then

echo -n "  Backing up Asterisk configs to /tmp/astbackup... "
mkdir /tmp/astbackup
cp /etc/asterisk/* /tmp/astbackup
echo "done."
echo
echo "  Uninstalling Asterisk 13..."
echo
zypper --non-interactive rm asterisk asterisk-dahdi asterisk-snmp
rm /usr/lib64/asterisk/modules/*opus*
if [ $? != 0 ]; then
	echo "    Something went wrong uninstalling Asterisk 13, exiting."
	exit 1
fi
echo "  done."
echo
echo "  Changing repositories to Asterisk 11..."
echo
mv /etc/zypp/repos.d/openSUSE-Leap-15.1-ViciDial-Ast13.repo /etc/zypp/repos.d/openSUSE-Leap-15.1-ViciDial-Ast11.repo
sed -i 's/Ast13/Ast11/g' /etc/zypp/repos.d/openSUSE-Leap-15.1-ViciDial-Ast11.repo
sed -i 's/asterisk-13/asterisk-11/g' /etc/zypp/repos.d/openSUSE-Leap-15.1-ViciDial-Ast11.repo
zypper --gpg-auto-import-keys --non-interactive refresh
if [ $? != 0 ]; then
	echo "    Something went wrong refreshing the repositories, exiting."
fi
echo "  done."
echo
echo "  Installing Asterisk 11..."
echo
zypper --non-interactive in asterisk asterisk-dahdi asterisk-snmp
if [ $? != 0 ]; then
	echo "    Something went wrong installing Asteriak 11, exiting."
	exit 1;
fi
echo "  done."
echo
echo "  Updating other associated packages..."
echo
zypper --non-interactive dup
echo "  done."
echo
echo -n "  Restoring Asterisk configs..."
echo
cp /tmp/astbackup/* /etc/asterisk/
cp /usr/src/astguiclient/trunk/docs/conf_examples/manager.conf.sample-1.8 /etc/asterisk/manager.conf
cp /usr/src/astguiclient/trunk/docs/conf_examples/extensions.conf.sample-1.8 /etc/asterisk/extensions.conf
echo "done."
echo
echo -n "  Reinstalling G729 and G723 codecs..."
echo
codec-install
echo "  done."
echo
echo -n "  Installed Asterisk version : "
asterisk -V
echo

fi
