#!/bin/bash

# askozia configuration backup script
# Author: Carsten Schoene <cs (at) linux-administrator (dot) com>
# Last change: 2010-09-30
set -x
#
# configuration options
HTTPUSER=admin						# user for web interface
HTTPPASS=askozia					# password for web interface
HTTPHOST=10.10.1.120					# IP address of askozia pbx
SCHEME=http						# http or https
BACKUPFILE=/backups/askozia-backup-current.xml		# directory and file where to store backup, dir must exist
SILENT=0						# silent mode 0/1
####################################################################################################

function usage {
	echo "Usage: $0"
	echo -e "\tConfiguration is done inside this script!"
	echo " "
	exit 1
}

if [ "$1" == "-h" ] || [ "$1" == "--help" ] ; then
	usage
fi

CURL=$(which curl)

if [ ! -x "${CURL}" ] ; then
	echo "curl not found!"
	exit 1
fi
case ${SCHEME} in
	http)
		OPTS=""
	;;
	https)
		OPTS="-k"
	;;
	*)
		echo "wrong scheme defined!"
		exit 2
	;;
esac

case ${SILENT} in
	0)
		SOPTS=""
	;;
	1)
		SOPTS="-s"
	;;
	*)
		echo "wrong silent value defined!"
		exit 3
	;;
esac

if [ -z "${HTTPUSER}" -o -z "${HTTPPASS}" -o -z "${HTTPHOST}" ] ; then
	echo "One of HTTPUSER, HTTPPASS or HTTPHOST is not defined!"
	exit 4
fi

if [ ! -d `dirname ${BACKUPFILE}` ] ; then
	echo "Backupdirectory does not exist!"
	exit 5
fi

# run silent and ignore unknown CA
${CURL} ${SOPTS} ${OPTS} \
 --user ${HTTPUSER}:${HTTPPASS} \
 ${SCHEME}://${HTTPHOST}/system_backup.php \
 --form Download=1 \
 --output ${BACKUPFILE}
RETVAL=$?
if [ "${RETVAL}" != "0" ] ; then

	if [ "${SILENT}" == "0" ] ; then
		echo " "
		echo "Automatic backup failed with error ${RETVAL}, see curl output for details"
		echo " "
		exit 6
	fi
else
	if [ "${SILENT}" == "0" ] ; then
		echo " "
		echo "Automatic backup succeeded"
		echo " "
		exit 0
	fi
fi
