#!/bin/bash
#
# LSE Leading Security Experts GmbH
# 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



