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

if ( 
    !empty($_POST)
    && !empty( $_POST['username'] )
    && !empty( $_POST['password'] )
    && !empty( $_POST['version'] ) ) {

    chdir(SITE_PATH);
    chdir("../");

    if ( !is_dir("cms-patching") ) {
        mkdir("cms-patching");
        
    }
    chmod("cms-patching", 0750);
    chdir("cms-patching/");

    // ----------- get current sys version -----------------

    if ( empty($_POST['current_sys_commit_hash']) ) {
        $_POST['current_sys_commit_hash'] = "latest";
    }

    if ( is_dir( $_POST['current_sys_commit_hash'] ) ) {
        exec("rm -rf ".$_POST['current_sys_commit_hash']); 
    }

    mkdir($_POST['current_sys_commit_hash']);
    chdir($_POST['current_sys_commit_hash']."/");

    // git
    $command = $_POST['git_path']." clone https://".$_POST['username'].":".$_POST['password']."@".$_POST['cms_repo']." ./";
    exec($command, $output, $result);

    if ( $result == 127 ) {
        die("false");
        /*
        $_POST['git_path'] = "/usr/local/bin/git";
        $command = $_POST['git_path']." clone https://".$_POST['username'].":".$_POST['password']."@".$_POST['cms_repo']." ./";
        exec($command, $output, $result);*/
    }

    if ( !empty($_POST['current_sys_commit_hash']) && $_POST['current_sys_commit_hash'] != 'latest' ) {
        exec($_POST['git_path']." checkout ".$_POST['current_sys_commit_hash']);
    }

    exec("chmod -R go-w ."); // fix permissions

    // ----------- get latest sys version -----------------

    chdir("../");

    // create or clean version dir
    if ( is_dir( $_POST['version'] ) ) {
        exec("rm -rf ".$_POST['version']); 
    }

    mkdir($_POST['version']);
    chdir($_POST['version']."/");

    // git
    $command = $_POST['git_path']." clone".(empty($_POST['cms_repo_branch']) ? "" : " -b ".$_POST['cms_repo_branch'] )." https://".$_POST['username'].":".$_POST['password']."@".$_POST['cms_repo']." ./";
    exec($command, $output, $result);

    if ( $result == 127 ) {
        die("false");
        /*
        $_POST['git_path'] = "/usr/local/bin/git";
        $command = $_POST['git_path']." clone".(empty($_POST['cms_repo_branch']) ? "" : " -b ".$_POST['cms_repo_branch'] )." https://".$_POST['username'].":".$_POST['password']."@".$_POST['cms_repo']." ./";
        exec($command, $output, $result);*/
    }

    if ( !empty($_POST['version']) && $_POST['version'] != 'latest' ) {
        exec($_POST['git_path']." checkout ".$_POST['version']);
    }

    exec("chmod -R go-w ."); // fix permissions

    die ("true");
}
if ( !empty($_POST['debug']) ) {
    die($command);
} else {
    die("false");
}