#!/bin/bash
#
# Copyright (C) 2022 Nethesis S.r.l.
# http://www.nethesis.it - nethserver@nethesis.it
#
# This script is part of NethServer.
#
# NethServer is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or any later version.
#
# NethServer 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with NethServer.  If not, see <http://www.gnu.org/licenses/>.
#
# exit when any command fails
set -e

# keep track of the last executed command
trap 'last_command=$current_command; current_command=$BASH_COMMAND' DEBUG
# echo an error message before exiting
trap 'echo "Roundcubemail DB restoration : \"${last_command}\" command returned exit code $?."' EXIT

source /opt/rh/rh-mariadb105/enable

if [[ ! -f '/var/lib/nethserver/backup/rh-mariadb105/roundcubemail.sql' ]]; then
    echo "[ERROR] Error the roundcubemail SCL mariadb105 dump does not exist"
    exit 1
fi

password=`perl -e "use NethServer::Password; print NethServer::Password::store('roundcubemail');"`
mysql --socket=/run/rh-mariadb105-mariadb/roundcubemail-mysql.sock -e "CREATE DATABASE IF NOT EXISTS roundcubemail;"
mysql --socket=/run/rh-mariadb105-mariadb/roundcubemail-mysql.sock --database roundcubemail < /var/lib/nethserver/backup/rh-mariadb105/roundcubemail.sql
mysql --socket=/run/rh-mariadb105-mariadb/roundcubemail-mysql.sock -e "ALTER DATABASE roundcubemail CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;"
mysql --socket=/run/rh-mariadb105-mariadb/roundcubemail-mysql.sock -e "grant all on roundcubemail.* to 'roundcubemail'@'localhost' identified by '$password';"
mysql --socket=/run/rh-mariadb105-mariadb/roundcubemail-mysql.sock -e "FLUSH PRIVILEGES"

rm -f /var/lib/nethserver/backup/rh-mariadb105/roundcubemail.sql
