#!/usr/bin/perl -w

#
# Copyright (C) 2016 Nethesis S.r.l.
# http://www.nethesis.it - support@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/>.
#

use NethServer::Password;

my $astdir = "/var/lib/asterisk";

#Restore dump of astdb 
if ( -r "$astdir/astdb.sqlite3.dump") 
{
	#astdb backup exists
	#remove astdb file if exists
	system ("/usr/bin/systemctl stop asterisk");
	if ( -e "$astdir/astdb.sqlite3" ) 
	{ 
		unlink "$astdir/astdb.sqlite3"; 
	}
	#create new astdb file from dump 
	if ($status = system ("/usr/bin/sqlite3 $astdir/astdb.sqlite3 < $astdir/astdb.sqlite3.dump")) 
	{
		exit bad_exit("restore dump of astdb", $status);
	} else {
		#change astdb ownership 
		system ("/bin/chown asterisk:asterisk $astdir/astdb.sqlite3");
	}
	system ("/usr/bin/systemctl start asterisk");
	unlink "$astdir/astdb.sqlite3.dump";
} else {
	print ("[INFO] Astdb backup doesn't exist\n");
}

#Restore dump of mysql 
if ( -r "$astdir/asterisk.dump")
{
    #asterisk mysql backup exists
	#drop mysql database if exists
	if ( system("/usr/bin/mysql --defaults-file=/root/.my.cnf -e 'use asterisk' &> /dev/null") == 0 ) #database exists
	{
		system("/usr/bin/mysql --defaults-file=/root/.my.cnf -e 'drop database asterisk' &> /dev/null");
	}	
	#create database
	system("/usr/bin/mysql --defaults-file=/root/.my.cnf -e 'create database asterisk' &> /dev/null");
	#put dump into db 
	system("/usr/bin/mysql --defaults-file=/root/.my.cnf asterisk < $astdir/asterisk.dump &> /dev/null");
	#require "apply changes"
	system("/usr/bin/mysql asterisk --defaults-file=/root/.my.cnf -e 'update admin set value=\"true\" where variable=\"need_reload\"' &> /dev/null");
	unlink "$astdir/asterisk.dump";
        my $managerpwd = `/usr/bin/mysql --defaults-file=/root/.my.cnf -BN asterisk -e 'select value from freepbx_settings where keyword = "AMPMGRPASS"'`;
        $managerpwd =~ s/\n//;
        system("/usr/bin/sed -i 's/^secret = .*/secret = ".$managerpwd."/g' /etc/asterisk/manager.conf");
} else {
    print ("[INFO] Asterisk mysql database backup doesn't exist\n");
}

sub bad_exit
{
    my ($phase, $status) = @_;

    warn("FreePBX backup restore failed! - status: $status\n");
    return $status / 256;
}

