#!/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
DATABASE_DUMP=$BACK_DIR/dbdump-$DATE.sql

getsql() {
	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`
}

if [ "$1" = "" ]; then
	echo "You need to specify a filename to restore!"
	exit 1
fi

FILENAME=$1
if [ ! -f $FILENAME ]; then
	echo "The file $FILENAME does not exist!"
	exit 2
fi

# Unpack backup
tar -C/ -zxf $FILENAME || exit 3

getsql

DATABASE_DUMP=`tar -ztf $FILENAME | grep var/lib.*.sql$`

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