#!/bin/bash

# Copyright: 2023 Virtuozzo International GmbH

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

# http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

[ -n "${MYSQLDUMPERLIB_VERSION:-}" ] && return 0;
MYSQLDUMPERLIB_VERSION="0.1";

include log;
include output;

$PROGRAM 'mysql';
$PROGRAM 'wget';
$PROGRAM 'gzip';

function Restore() {

		while [ "$1" != "" ]; 
		do
		  case $1 in
		    -u | --user )     shift
		      local user="$1"
		      ;;
		    -p | --password ) shift
		      local password="$1"
		      ;;
		    -d | --dumpUrl )  shift
		      local dumpurl="$1"
		      ;;
		    -b | --dbname )   shift
		      local database="$1"
		      ;;
		  esac
		  shift
		done

	[ ! -e "/var/cache" ] && mkdir -p "/var/cache/";
        local dumpfile="/var/cache/tempdump$$.dump";
        $WGET --no-check-certificate $dumpurl -O $dumpfile >> $ACTIONS_LOG 2>&1;
        $GZIP -l ${dumpfile} > /dev/null 2>&1 && { mv "${dumpfile}" "${dumpfile}.gz" &&  $GZIP -d  "${dumpfile}.gz" && mv "${dumpfile}" "${dumpfile}.sql"; } || { mv "${dumpfile}" "${dumpfile}.sql"; }
        [ -s ${dumpfile}.sql ] || return 74;
        MYSQL_PWD=${password} $MYSQL -s -u${user} --execute="CREATE DATABASE IF NOT EXISTS $database" >> $ACTIONS_LOG 2>&1 || return 72;
        MYSQL_PWD=${password} $MYSQL -s -u${user} $database < ${dumpfile}.sql || return 73;
        [ -f ${dumpfile}.sql ] && rm -f ${dumpfile}.sql;
}

