#!/opt/bin/sh

get_part_label() {
echo "All the partitions of the external storage are specified below:";echo
ls /tmp/mnt -F | grep "@" | sed "s/@//g";echo
while true
do
	echo; echo -n "Input the label of the partition to backup Asterisk: "
	read partLabel
	if [ "$(ls /tmp/mnt/ | grep -x ${partLabel})" == "$partLabel" ] 
	then break
	else echo "ERROR! Partition '$partLabel' doesn't exist!"
	fi
done
echo "Partition '${partLabel}' was selected."
}

backup_ast() {
filename=backup-int-`date "+%Y-%m-%d_%H-%M"`.tar.gz
tar cvzf /tmp/mnt/${partLabel}/${filename} -C /opt/ bin etc home lib root sbin share tmp usr var
echo; echo "Backup file /tmp/mnt/${partLabel}/${filename} has been created."
}

check_usb_drive() {
while true
do
	if [ "$(ls /tmp/mnt)" == "" ]
	then echo "Please, plug a USB drive to your Keenetic device. When done, press Enter"; read userInput
	else break
	fi
done
}


#============================ MAIN ============================
echo
echo "This script will backup your Asterisk installation from the internal storage to your USB drive."
echo -n "Continue? <y/n>"; read userInput; if [ "$userInput" != "y" ]; then exit; fi
check_usb_drive; get_part_label
echo; echo -n "Are you ready to start backup? <y/n>"; read userInput
if [ "$userInput" == "y" ]; then backup_ast; else exit; fi
echo; echo "When you need to restore your installation from the backup file to the internal storage of your Keenetic device, follow the steps below:"
echo "1. create an ext4 partition of at least 150 MB on your USB drive;"
echo "2. create /install directoty on the ext4 partition;"
echo "3. place the backup file '${filename}' into the /install directory and into the root directory of the ext4 partition;"
echo "4. plug your USB drive to your Keenetic device;"
echo "5. open web configurator of your Keenetic device in web browser, go to Management>OPKG>OPKG package manager, choose the partition containing the backup file and click 'Save' in the bottom of the page;"
echo "6. at this step your Entware Asterisk installation is started on the USB drive. Connect to your Keenetic device via ssh, open Linux shell of your Entware installation, execute the command 'restore' and follow instructions in order to restore to the internal storage."
echo; echo "Press any key to exit the script"; read userInput
exit

