<?php
	error_reporting(E_ALL & ~E_NOTICE);
	ini_set('display_errors', 1);
	set_time_limit(12000);
	ini_set('memory_limit' , '512M');

	header('Content-type: application/json; charset=UTF-8' );
	header('Access-Control-Max-Age: 0');
	
	require_once('../install/functions.php');
	require_once('../install/dictionary.php');
	$ret =  [
		'ok' => 0,
		'msg' => ''
	];
	global $pdo;
	$dots = "------------------------------------------------";
	$app_folder = 'pegasus_cloud_app';
	$log = '';
	$step = '';

	$islocl = 0;
	if(!empty($_REQUEST['islocl'])){
		$islocl = 1;
	}

	if(!isset($_REQUEST['action'] )){
		$_REQUEST['action'] = 'dostep';
	}

	if(check_if_app_exist()){
		// echo '<span style="color:red;font-weight:bold">' . $dic['app_is_already_install'] . '</span>';
		$ret['msg'] = $dic['app_is_already_install'] ;
		echo json_encode($ret);
		return ;
	}

	
	if(!empty($_REQUEST['step']) && in_array(strtolower($_REQUEST['step']), array('unzip', 'copy', 'upload', 'copyjs')) ){
		$step = strtolower($_REQUEST['step']);
	}

	if( $_REQUEST['action'] == 'getstartmsg'){
		$ret['ok'] = 1;
		switch($step){
			case 'unzip': 
				$log =  "$dots\n";
				if(!is_dir('install_files/install')){
				
					$log .= "--- Unzipping installation files\n"  ;

					
				}else{
					$log .= "--- Files have been unzipped\n";
				}
				$log .=  "$dots\n";
				
				$ret['msg'] = $log;
				echo json_encode($ret);
				return ;
			case 'copy': 
				if($islocl==0  && ( !isset($_REQUEST['cpfolder']) || empty($_REQUEST['cpfolder']) ) ){
					$log .= "$dots\n";
					if($_REQUEST['upd_rcopy']<1){
						$log .= "--- Copying files via FTP \n"  ;
					}else{
						$log .= "--- Copying files \n"  ;
					}
					$log .= "$dots\n"; 
					$ret['msg'] = $log;
				}
				
				echo json_encode($ret); 
				return;
			case 'upload':
				echo json_encode($ret); 
				return;
			default:
				die('Underfinted type');
		}
	}elseif($_REQUEST['action'] == 'dostep'){
		
		switch($step){
			case 'unzip':  
				if(!is_dir('install_files/install')){
					install_unzip_file('install.zip');
					$log = "$dots\n".
					"--- Installation files have been unzipped successfully \n"  . 
					"$dots\n";
				}
				$ret['ok'] = 1;
				$ret['msg'] = $log;

				if($islocl==1){ 
					$ret['next'] = 'upload'; 
				}else{
					$ret['next'] = 'copy';	
				}

				echo json_encode($ret);
				return ;
			case 'copy': 
				$ok=0;
				$cpfolder = '/';
				$cpsubfolder = '';
				$cur_cpfolder = '';
				$cur_cpsubfolder = '';
				$log;

				if(isset($_REQUEST['cpfolder'])){
					if(mb_strpos($_REQUEST['cpfolder'], ',')>0){
						$tmpstr = mb_substr($_REQUEST['cpfolder'], 0, mb_strpos($_REQUEST['cpfolder'], ',')); 
						
						if(in_array($tmpstr , array('css',  'pegasus', 'images',  'js', 'pegasus_cloud_app',  'photos', 'tmp') )){
							$cur_cpfolder  =  $tmpstr ; 
							$cpfolder = $_REQUEST['cpfolder'];
							if(isset($_REQUEST['cpsubfolder']) && mb_strpos($_REQUEST['cpsubfolder'], ',')>0 ){ 
								$cpsubfolder = $_REQUEST['cpsubfolder'];
								$cur_cpsubfolder = mb_substr($_REQUEST['cpsubfolder'], 0, mb_strpos($_REQUEST['cpsubfolder'], ',')); 
							}
						}else{
							$ret['ok'] = 0;
							$ret['msg'] = "Undefined Folder '$tmpstr'";
						}


					} 
				}
				if($islocl==1){
					$ret['ok'] = 1;
					$ret['msg'] = $log;
					$ret['next'] = 'upload';
					echo json_encode($ret);
					return;
				}
				$overFtp = false;
				$conn_id;
				if($_REQUEST['upd_rcopy']<1){
					$overFtp = true;
					$conn_id = install_ftp_connect();
					if(!$conn_id){
						$ret['ok'] = 0;
						$ret['msg'] = 'install_ftp_connect returned false';
						return;
					}

				}

				// if($cpfolder!='/'){
				// 	$log .= 
				// }else{

				// }

				if($cur_cpfolder == 'pegasus_cloud_app'){
					if(!empty($cur_cpsubfolder)){
						$start = time();
						do{
							if($overFtp){
								list($ok, $log00) = install_ftp_putAll(
									$conn_id , 
									'../install/install_files/install/files/' .$cur_cpfolder .'/'.$cur_cpsubfolder 
									, $_REQUEST['ftp_path']  . '/'. $cur_cpfolder.'/'.$cur_cpsubfolder
								);
								if($ok){
									$log.=$log00;
								}
							}else{
								list($ok, $log00) = install_copyFiles(
									'../install/install_files/install/files/' .$cur_cpfolder .'/'.$cur_cpsubfolder , 
									'../'. $cur_cpfolder.'/'.$cur_cpsubfolder
								);
								if($ok){
									$log.=$log00;
								}
							}



								
							if(!empty($cpsubfolder)){
								$cpsubfolder = str_replace(',' .$cur_cpsubfolder.',','', ',' .$cpsubfolder); 
								if(!empty($cpsubfolder) && mb_strpos($cpsubfolder , ',')>0 ){  
									$cur_cpsubfolder = mb_substr($cpsubfolder, 0, mb_strpos($cpsubfolder, ',')); 
								} 
							}
							if(empty($cpsubfolder ) && !empty($cpfolder)){ 
								$cpfolder = str_replace(',' .$cur_cpfolder.',','', ',' . $cpfolder);
								break;
							}

						}while( (time() - $start)<30 ); 
					}else{
						if($overFtp){
							list($ok, $log, $cpsubfolder) = install_ftp_putAll(
								$conn_id , 
								'../install/install_files/install/files/' .$cur_cpfolder,
								$_REQUEST['ftp_path']  . '/'. $cur_cpfolder ,
								array( 'recursively' => false) 
							);
						}else{
							list($ok, $log, $cpsubfolder) = install_copyFiles(
									'../install/install_files/install/files/' .$cur_cpfolder   , 
									'../'. $cur_cpfolder,
									array('folderPermission'=>0755,'filePermission'=>0644, 'recursively' => false) );
						}

						
							
					}

				}elseif($cpfolder!='/'){
					if($overFtp){ 
						list($ok, $log) = install_ftp_putAll(
							$conn_id , 
							'../install/install_files/install/files/' .$cur_cpfolder,
							$_REQUEST['ftp_path']  . '/'. $cur_cpfolder  
						);
					}else{
						list($ok, $log) = install_copyFiles( '../install/install_files/install/files/' .$cur_cpfolder  , '../'. $cur_cpfolder);
					}
					if(!empty($cpfolder)){
						$cpfolder = str_replace(',' .$cur_cpfolder.',','',',' .$cpfolder);
					}
				}else{
					if($overFtp){ 
						list($ok, $log, $cpfolder) = install_ftp_putAll(
							$conn_id , 
							'../install/install_files/install/files/' ,
							$_REQUEST['ftp_path']  . '/'  ,
							array( 'recursively' => false) 
						);
					}else{
						list($ok, $log, $cpfolder) = install_copyFiles( 
							'../install/install_files/install/files'   ,
								'../', array('folderPermission'=>0755,'filePermission'=>0644, 'recursively' => false) ); 
					}

				}

				 
				if(empty($cpfolder)){
					$log .= "$dots\n";
					if($_REQUEST['upd_rcopy']<1){
						$log .= "--- Files have been copied via FTP successfully\n"  ;
					}else{
						$log .= "--- Files have been copied successfully\n"  ;
					}
					$log .= "$dots\n"; 
				}
				$ret['ok'] = $ok;
				$ret['msg'] = $log;
				
				// if($islocl==0){
				// 	$ret['next'] = 'copyjs';
				// }else{
				// 	$ret['next'] = 'upload';
				// }
				// $ret['next'] = 'upload';
				if(!empty($cpfolder)){
					$ret['next'] = 'copy';
					$ret['cpfolder'] = $cpfolder; 
					$ret['cpsubfolder'] = $cpsubfolder;  
				}else{
					$ret['next'] = 'upload';
				}
					
				echo json_encode($ret);
				return;
			case 'upload':
				$log .=  "$dots\n";
				$log .=  "--- Upload sql file \n"  ;
				$log .=  "$dots\n";
				install_mysql_upload_sql( '../install/install_files/install/sql/install.sql',$islocl );
			
				
		
				if(file_exists('../pegasus_cloud_app/core_libs/pegConfigFile.php')){
					$log .=  "$dots\n";
					$log .=  "--- Make peg-config.php\n"  ;
					$log .=  "$dots\n";

					require_once '../pegasus_cloud_app/core_libs/pegConfigFile.php';
					require_once '../pegasus_cloud_app/core_kernel/pegasus_functions00.php';
					require_once '../pegasus_cloud_app/core_kernel/pegasus_file_functions.php';

					if($islocl){
						$approot = $_REQUEST['apppath'];
						define('WEBAPP_MAIN_PATH', "$approot/pegasus_cloud_app" );
						$pdo->query("update cor000 set https_only=0;");
					}else{
						define('WEBAPP_MAIN_PATH', 'pegasus_cloud_app');
					}

					define('DB_HOST', $_REQUEST['mysql_host'] .':' .  $_REQUEST['mysql_port']);
					define('DB_USER', $_REQUEST['mysql_user']); 
					define('DB_PASSWORD', $_REQUEST['mysql_pass']); 
					define('DB_NAME', $_REQUEST['mysql_db']);  
					
					$pegConfigFile = new pegConfigFile(1);
					$getcwd = getcwd();
					chdir('../pegasus_cloud_app/core01/');
					$pegConfigFile->generateConfigurationFile(); 
					chdir($getcwd);
					
					$copy_return  = copy( '../tmp/pegconf/peg-def.php' , '../pegasus_cloud_app/peg-config.php');
					if($copy_return){
						$log .=  "$dots\n";
						$log .=  "--- copy '../tmp/pegconf/peg-def.php' to '../pegasus_cloud_app/peg-config.php' failed \n"  ;
						$log .=  "$dots\n";
					}

					chmod('../pegasus_cloud_app/peg-config.php' , 0644); 
				}else{
					$log .=  "$dots\n";
					$log .=  "--- Make pegasus.ini\n"  ;
					$log .=  "$dots\n";
					$pegasus_ini = "[mysql_server_section]\n".
						"\tmysql_host = \"" . $_REQUEST['mysql_host'] .':' .  $_REQUEST['mysql_port'] . "\"".PHP_EOL.
						"\tmysql_db   = \"" . $_REQUEST['mysql_db'] . "\"".PHP_EOL.
						"\tmysql_user = \"" . $_REQUEST['mysql_user'] . "\"".PHP_EOL.
						"\tmysql_pass = \"" . $_REQUEST['mysql_pass'] . "\"".PHP_EOL;
					
					
					if($islocl){
						$approot = $_REQUEST['apppath'];
						$pegasus_ini .= "[webapp_app_section] ".PHP_EOL."\t web_app_main_path = \"".$approot ."/pegasus_cloud_app\" ".PHP_EOL;
					}
					
					$fp = fopen('../'.$app_folder.'/pegasus.ini', 'w');
					fwrite($fp, $pegasus_ini);
					fclose($fp);
					
				}
			


				$log .=  "$dots \n ";
				$log .=  "--- Update Parameters \n"  ;
				$log .=  "$dots\n ";
			
				$sftp='0';
				if(isset($_REQUEST['sftp']) && ($_REQUEST['sftp']=='1')){
					$sftp='1';
				}
				
				$passv = 0;
				if(isset($_REQUEST['passv']) && ($_REQUEST['passv']=='1')){
					$passv = 1;
				}
			
				$upd_rcopy = 0;
				if(isset($_REQUEST['upd_rcopy']) && ($_REQUEST['upd_rcopy']=='1')){
					$upd_rcopy = 1;
				}
				
				$query = "update cor000 set
									ftp_user=\"" .$_REQUEST['ftp_user']. "\" ,
									ftp_pass=\"" .$_REQUEST['ftp_pass']. "\" ,
									ftp_path=\"" .$_REQUEST['ftp_path']. "\" ,
									ftp_port=\"" .$_REQUEST['ftp_port']. "\" ,
									tesae_user=\"" .$_REQUEST['tesae_user']. "\" ,
									tesae_pass=\"" .$_REQUEST['tesae_pass']. "\" ,
									sftp=\"" . $sftp . "\",
									upd_rcopy=\"" . $upd_rcopy . "\",
									ftp_pasv=\"" . $passv . "\"
									";
				$pdo->query($query);
				if($islocl){
					$pdo->query("delete from p72;");
					$pdo->query("delete from p73;");
				}
			
				$ret['ok'] = 1;
				$ret['msg'] = $log; 
				$ret['next']='';
				echo json_encode($ret);
				return;
			default:
				die('Underfinted type');
			
		}
	}
	return ; 
?>