<?php
/********************************************************************************
 * (c)1337 aheadware.com - All rights reserved
 ********************************************************************************/
include_once 'build_inc.php';

require_once __DIR__ . '/../../src/server/config/boot_global.php';
require_once __DIR__ . '/../../src/server/config/boot_local.php';

function installLiveDBOnLocal() {
    global $remote_backup_dir;
    global $local_temp_dir;

    $yesterday = date( 'Y-m-d', (time() - 60 * 60 * 24) );
    $backupName = 'dbdump' . $yesterday . '.zip';

    debug ( "Connect..." );
    sshConnect();

    debug ( "Download dump..." );
    sshFileDownload( $remote_backup_dir . '/tbuddy/' . $backupName, $local_temp_dir . '/dbdump.zip' );

    debug ( "Extract dump..." );
    localMkdir( $local_temp_dir . '/dbdump' );
    $zip = new ZipArchive();
    $res = $zip->open( $local_temp_dir . '/dbdump.zip' );
    if ( true == $res ) {
        $zip->extractTo( $local_temp_dir . '/dbdump' );
    }

    debug ( "Import SQL dump..." );
    windowsCmd( 'c:\wamp\bin\mysql\mysql5.6.17\bin\mysql.exe -uroot tb_core < ' .  $local_temp_dir .  '/dbdump/tbcore.sql' );
    windowsCmd( 'c:\wamp\bin\mysql\mysql5.6.17\bin\mysql.exe -uroot tb_teamdata < ' . $local_temp_dir . '/dbdump/tbteamdata.sql' );

    debug ( "Set master password..." );
    $masterPW = TB_Shared_Utils_Security::getSaltedPassword( 'test' );
    $dbCore = TB_Shared_Db_Core::get();

    $sql = 'UPDATE ' . TB_Shared_Ent_Core_Account::getTable() . ' SET pass = :password';

    $stmt = $dbCore->prepare( $sql );
    $stmt->execute( array( ':password' => $masterPW ) );

    debug ( "Done." );
}

installLiveDBOnLocal();