#!/bin/sh
#
#  copyright 2014 Cornelius Kölbel
#  License:  AGPLv3
#  contact:  http://www.privacyidea.org
#
# This code is free software; you can redistribute it and/or
# License as published by the Free Software Foundation; either
# version 3 of the License, or any later version.
#
# This code is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU AFFERO GENERAL PUBLIC LICENSE for more details.
#
# You should have received a copy of the GNU Affero General Public
# License along with this program.  If not, see <http://www.gnu.org/licenses/>. 
#
#
# This script creates a backup of all privacyidea components at
# /var/lib/privacyidea/backup
BACK_DIR=/var/lib/privacyidea/backup
CONF_DIR=/etc/privacyidea/
RADIUS_CLIENTS=/etc/freeradius/clients.conf
INIFILE=$CONF_DIR/privacyidea.ini
DATE=`date +"%y%m%d-%H%M%S"`
BASE_NAME="privacyidea-backup"
DATABASE_DUMP=$BACK_DIR/dbdump-$DATE.sql


SQLALCHEMY=`grep "^sqlalchemy.url" $INIFILE`

MYSQL=`echo $SQLALCHEMY | cut -d: -f1 | cut -d= -f2`
# should be " mysql"
DATABASE=`echo $SQLALCHEMY | cut -d'/' -f4`
UPWHOST=`echo $SQLALCHEMY | cut -d'/' -f3`
HOST=`echo $UPWHOST | cut -d@ -f2`
USER=`echo $UPWHOST | cut -d@ -f1 | cut -d: -f1`
PASSWORD=`echo $UPWHOST | cut -d@ -f1 | cut -d: -f2`

# Dump DB
if [ "$MYSQL" = " mysql" ]; then
	mysqldump -u $USER --password=$PASSWORD -h $HOST $DATABASE > $DATABASE_DUMP
fi

mkdir -p $BACK_DIR
tar -zcf $BACK_DIR/$BASE_NAME-$DATE.tgz $CONF_DIR $RADIUS_CLIENTS $DATABASE_DUMP

rm -f $DATABASE_DUMP
