#!/bin/bash
# -*- coding: utf-8 -*-
#
#    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
#

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

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`
BACKUPFILE=linotp_backup_${DATUM}.sql
BACKUPKEY=encKey_${DATUM}.gpg

echo "--------- LSE LinOTP 2 backup -----------------------"
echo "----- Backing up encryption Key ---------------------" 
echo "Think of a good passphrase you can remember well..."
echo

gpg -c --cipher-algo AES256 -o $BACKUPKEY $ENCFILE

echo "----- Backing up token database ---------------------" 
echo "We will now backup the database <<$DATABASE>> on the host <<$HOST>>."
echo "This will be done with the user <<$USERNAME>>."
echo "The database will be written to <<$BACKUPFILE>>."
echo -n "..."
mysqldump --user="$USERNAME" --password="$PASSWORD" --host="$HOST" $DATABASE > $BACKUPFILE
if [ $? == 0 ]; then
	echo "done."
else
	echo "failed!"
	exit 1
fi



