<?php
$cms_root_path = "../../../";
require_once($cms_root_path."includes/compatibility_includer.php");

require_once ('../libs/Diff/Diff.php');
require_once ('../libs/Diff/Diff/Renderer/Html/RSSideBySide.php');
require_once ('../libs/Diff/Diff/Renderer/Html/Array.php');

$cms_patching = CmsPatching::newInstance()
    ->loadInfo("../")
    ->loadConfig("../config.json")
;

/*$response = array(
    'success' => false,
    'html' => ''
);*/

if ( empty( $_REQUEST ) || empty( $_REQUEST['git_path'] ) || empty( $_REQUEST['version'] ) ) {
    //die(json_encode($response));
    die("false");
}

$files = array();
if ( !empty($_REQUEST['files']) ) {
    $files = $_REQUEST['files'];
}

$html = "";
$renderer = new Diff_Renderer_Html_RSSideBySide;
$files_that_need_to_be_backed_up = array();
$files_that_need_to_be_replaced_or_inserted = array();
for ($i=0; $i < count($files); $i++) { 

    /*$file = array(
        'filename':$files[$i]['filename'],
        'source':$files[$i]['source'],
        'destination':$files[$i]['destination'],
        'mode':$files[$i]['mode']
    );*/

    $fetched_version = false;
    if ( file_exists($files[$i]['source']) ) {
        if ( is_dir($files[$i]['source']) ) {
            $fetched_version = "";
        } else {
            $fetched_version = $cms_patching->fileContentAsString($files[$i]['source']);
        }
    }
    $current_system_version = false;
    if ( file_exists($files[$i]['destination']) ) {
        if ( is_dir($files[$i]['destination']) ) {
            $current_system_version = "";
        } else {
            $current_system_version = $cms_patching->fileContentAsString($files[$i]['destination']);
        }
    }

    $file_doesnt_exist_in_version = false;
    if ( $fetched_version === false ) {
        $file_doesnt_exist_in_version = true;
        $fetched_version = "";
    }

    $file_doesnt_exist_in_current_sys = false;
    if ( $current_system_version === false ) {
        $file_doesnt_exist_in_current_sys = true;
        $current_system_version = "";
    }

    $b = explode("\n", $fetched_version);
    $a = explode("\n", $current_system_version);
    $diff = new Diff($a, $b, array('ignoreWhitespace'=>true));
    $html = $diff->Render($renderer);

    if ( !empty($html) && file_exists($files[$i]['destination']) ) {
        $files_that_need_to_be_backed_up[] = $files[$i];
    }

    if ( !empty($html) && $file_doesnt_exist_in_version === false || $file_doesnt_exist_in_current_sys === true && $file_doesnt_exist_in_version === false ) {
        $files_that_need_to_be_replaced_or_inserted[] = $files[$i];
    }
}

echo "<br/><br/>";

$backup_dir = "../backup/".time();
echo "Creating backup directory ".$backup_dir." <br/><br/>\n\n";
mkdir($backup_dir);

foreach ($files_that_need_to_be_backed_up as $file) {
    echo "Backing up ".$file['destination']."... <br/>\n";
    if ( is_dir($file['destination']) ) {
        echo "Backing up directory <br/><br/>\n\n";
        mkdir($file, 0777, true);
    } else if ( file_exists($file['destination']) ) {
        $path_parts = pathinfo($file['destination']);
        echo "Checking if backup target directory (".$backup_dir.$path_parts['dirname'].") exists <br/>\n";
        if (!file_exists($backup_dir.$path_parts['dirname'])) {
            echo "Creating backup target directory (".$backup_dir.$path_parts['dirname'].") <br/>\n";
            mkdir($backup_dir.$path_parts['dirname'], 0777, true);
        }
        if ( !file_exists($backup_dir.$file['destination']) ) {
            echo "Backing up ".$file['destination']." to ".$backup_dir.$file['destination']." <br/><br/>\n\n";
            copy($file['destination'], $backup_dir.$file['destination']);
        } else {
            echo "File is already backed up (".$backup_dir.$file['destination'].") <br/><br/>\n\n";
        }
    }
}

foreach ($files_that_need_to_be_replaced_or_inserted as $file) { 
    echo "Updating/Inserting ".$file['destination']."... <br/>\n";
    if (file_exists($file['destination']) && !is_dir($file['destination'])) {
        echo "Deleting existing copy ".$file['destination']."... <br/>\n";
        unlink($file['destination']);
    }
    if ( file_exists($file['source']) && is_dir($file['source']) ) {
        mkdir($file['destination'], 0755, true);
        echo "Created ".$file['destination']."<br/><br/>\n\n";
    } else {
        // check if the directory is there to be coppied into
        $path_parts = pathinfo($file['destination']);
        if (!file_exists($path_parts['dirname'])) { 
            echo "Creating directory ".$path_parts['dirname']." for ".$file['destination']."<br/>\n";
            mkdir($path_parts['dirname'], 0755, true);
        }
        echo "Copying over ".$file['source']." to ".$file['destination']."<br/><br/>\n\n";
        copy($file['source'],$file['destination']);
    }
}

$downloaded_repo_location = SITE_PATH."/../cms-patching/".$_REQUEST['version']."/";
$new_version_commit_hash = exec("cd ".$downloaded_repo_location." && ".$_REQUEST['git_path']." rev-parse HEAD");

// Updating version number
echo "Updating current version number from  ".$cms_patching->info['original_version']." to ".$new_version_commit_hash."<br/><br/>\n\n";
$cms_patching->info['version_number'] = $new_version_commit_hash;
$cms_patching->saveInfoTxt('version_number');

if ( empty($cms_patching->info['original_version']) || $cms_patching->info['original_version'] == "ae570bf" ) {
    echo "First time updating this system!<br/><br/>\n\n";
    $cms_patching->info['original_version'] = $new_version_commit_hash;
    $cms_patching->saveInfoTxt('original_version');
}

die("good job - you deserve a nap!");