#!/bin/bash

#
#    LinOTP - the open source solution for two factor authentication
#    Copyright (C) 2010 - 2014 LSE Leading Security Experts GmbH
#
#    This file is part of LinOTP server.
#
#    This program is free software: you can redistribute it and/or
#    modify it under the terms of the GNU Affero General Public
#    License, version 3, as published by the Free Software Foundation.
#
#    This program 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/>.
#
#
#    E-mail: linotp@lsexperts.de
#    Contact: www.linotp.org
#    Support: www.lsexperts.de
#

# Restore encryption Key of LinOTP server and the database
#
# rev01: initial release

if [ $@!=2 ]; then
	echo "Missing parameter!"
 	echo "$0 <sql-dump-file> <encKey-File>"
 	exit 1
fi

DUMPFILE=$1
BACKUPKEY=$2

ENCFILE=/etc/linotp2/encKey
LINOTPCONFIG=/etc/linotp2/linotp.ini
ALCHEMYURL=`grep ^sqlalchemy.url /etc/linotp2/linotp.ini | cut -d '=' -f2`
USERNAME=`echo $ALCHEMYURL | cut -d: -f2 | cut -d'/' -f 3-`
PASSWORD=`echo $ALCHEMYURL | cut -d: -f3- | cut -d '@' -f1`
HOST=`echo $ALCHEMYURL | cut -d'@' -f2- | cut -d'/' -f1`
DATABASE=`echo $ALCHEMYURL | cut -d'@' -f2- | cut -d'/' -f2`
DATUM=`date +%y%m%d%H%M`


echo "--------- LSE LinOTP 2 Restore-----------------------"
echo "----- Restoring encryption Key ----------------------" 
echo "You need to enter the passphrase you provided when you backed up the encryption key"
echo

gpg -d -o $ENCFILE $BACKUPKEY
if [ $? != 0 ]; then
	echo "Error decrypting encKey".
	exit 1
fi

echo "----- Restoring token database ----------------------" 
echo "We will now restore the database <<$DATABASE>> on the host <<$HOST>>."
echo "This will be done with the user <<$USERNAME>>."
echo "The database will be read from <<$DUMPFILE>>."
echo -n "..."
mysql --user="$USERNAME" --password="$PASSWORD" --host="$HOST" $DATABASE < $DUMPFILE
if [ $? == 0 ]; then
	echo "done."
else
	echo "failed!"
	exit 1
fi



