#!/usr/bin/php
<?php
/* vim: set expandtab tabstop=4 softtabstop=4 shiftwidth=4:
  Codificación: UTF-8
  +----------------------------------------------------------------------+
  | Elastix version 2.0                                                  |
  | http://www.elastix.org                                               |
  +----------------------------------------------------------------------+
  | Copyright (c) 2006 Palosanto Solutions S. A.                         |
  +----------------------------------------------------------------------+
  | Cdla. Nueva Kennedy Calle E 222 y 9na. Este                          |
  | Telfs. 2283-268, 2294-440, 2284-356                                  |
  | Guayaquil - Ecuador                                                  |
  | http://www.palosanto.com                                             |
  +----------------------------------------------------------------------+
  | The contents of this file are subject to the General Public License  |
  | (GPL) Version 2 (the "License"); you may not use this file except in |
  | compliance with the License. You may obtain a copy of the License at |
  | http://www.opensource.org/licenses/gpl-license.php                   |
  |                                                                      |
  | Software distributed under the License is distributed on an "AS IS"  |
  | basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See  |
  | the License for the specific language governing rights and           |
  | limitations under the License.                                       |
  +----------------------------------------------------------------------+
  | The Original Code is: Elastix Open Source.                           |
  | The Initial Developer of the Original Code is PaloSanto Solutions    |
  +----------------------------------------------------------------------+
 */

/*
This script takes two argument, the first is the action (install,update,delete)
and the second argument is the database folder path where are files sqls. 
This script install, update and delete database.
*/

if ($argc < 3){
   die("Please specify the action and folder path files sqls.\n Usage: {$_SERVER['argv'][0]} install /usr/share/elastix/.../db/  version sql_export\n");
}

$documentRoot="/var/www/html";
require_once("$documentRoot/libs/misc.lib.php");
require_once("$documentRoot/configs/default.conf.php");
//global variables framework
global $arrConf;
require_once("$arrConf[basePath]/libs/paloSantoConfig.class.php");

$arrActions = array("install","update","delete");

if(isset($_SERVER['argv'][1]) & in_array($_SERVER['argv'][1],$arrActions)){
   if(isset($_SERVER['argv'][2])){
      $action      = $_SERVER['argv'][1];
      $path_folder = $_SERVER['argv'][2]; 
	  $sql_export  = isset($_SERVER['argv'][4])?$_SERVER['argv'][4]:false; 
      $arrFiles    = scandir("$path_folder/$action");

      if(is_array($arrFiles) && count($arrFiles)>0){
          $password="";
          if($sql_export==false){
              $confElastix = new paloConfig("/etc","elastix.conf"," = ","[[:space:]]*=[[:space:]]*");
              $contentFile = $confElastix->leer_configuracion();
              $password    = $confElastix->privado_get_valor($contentFile,"mysqlrootpwd");
          }

          if($action=="install"){
             return executeFiles_SQL_install($arrFiles, $password, $path_folder, $action, $sql_export);
          }
	  else if($action=="update"){
     	      $version = isset($_SERVER['argv'][3])?$_SERVER['argv'][3]:false;
	      if(isset($version) && !empty($version))
	          return executeFiles_SQL_update($version, $password, $path_folder, $action, $sql_export);
              else
    	          echo "Has not been passed the version to the process of updating.\n";
              return 0;
          }
          else if($action=="delete"){
             echo "Nothing to be done in database. The action $action did have implementation yet.\n";
             return 0;
          }
      }
      else{
         echo "Nothing to be done. The action $action did not find any sql file, in $path_folder/$action\n";
      }
   }
   else{
      echo "Error: second arg not defined. Usage: {$_SERVER['argv'][0]} action path_folder_files_sqls\nThe actions will be: install, update and delete.\n";
      return 1;
   }
}
else{
   echo "Error: first arg not defined. Usage: {$_SERVER['argv'][0]} action path_folder_files_sqls \n The actions will be: install, update and delete.\n";
   return 1;
}

function executeFiles_SQL_install($arrFiles, $password, $path_folder, $action, $sql_export=false)
{
   if(is_array($arrFiles) && count($arrFiles)>0){
      foreach($arrFiles as $k => $file){// must only have sqls files valids.
         if(ereg("\.sql$",$file)){
	     if($sql_export==false){
            	echo "Executing mysql -uroot -p$password < $path_folder/$action/$file ... \n";
	        exec("mysql -uroot -p$password < $path_folder/$action/$file",$arrConsole,$flatStatus);

    	        echo "RETURN $flatStatus\n";
        	if($flatStatus != 0){
	            print_r($arrConsole);
	            echo "Error, Action $action database failed.\n";
		    return 1;
		}
	     }
	     else{
	            echo  file_get_contents("$path_folder/$action/$file");
	     }			
         }
      }

      if($sql_export==false)
          echo "Successfull, Action $action database.\n";
      return 0;
   }
   echo "Nothing to be done in database.\n";
   return 0;
}

function executeFiles_SQL_update($version, $password, $path_folder, $action, $sql_export=false)
{
    $stringsql = updatedatabase($version,$path_folder);

    if(!is_null($stringsql) && !empty($stringsql)){
        if($sql_export==false){
            echo "Updating since $version\n";
            $fileupdate = "$path_folder/$action/01-updates-database.sql";
            file_put_contents($fileupdate,$stringsql);

            echo "Executing mysql -uroot -p$password <  $fileupdate... \n";
            exec("mysql -uroot -p$password < $fileupdate",$arrConsole,$flatStatus);

            echo "RETURN $flatStatus\n";
            if($flatStatus != 0){
                echo "Error, Action $action database failed.\n";
                return 1;
            }
            else{
                echo "Successfull, Action $action database.\n";
                return 0;
            }
        }
        else{
            echo $stringsql;
            return 0;
        }
    }
    echo "Nothing to be done in database.\n";
    return 0;
}

function esmayor($cadenainteractual,$cadenadada)
{
     $versionreleasedada=split("-",$cadenadada);     
     $versionreleaseinteractual=split("-",$cadenainteractual);
        if($versionreleasedada[0]<$versionreleaseinteractual[0])
            return true;
        else if($versionreleasedada[0]==$versionreleaseinteractual[0])
        {
            $number="[[:digit:]]+";
            $curso="[a-zA-Z]+$";
            ereg("^($number)($curso)*",$versionreleasedada[1],$regsdada);
            ereg("^($number)($curso)*",$versionreleaseinteractual[1],$regsactual);
            if(cursor($regsdada[2])<cursor($regsactual[2]))
                return true;
            else if(cursor($regsdada[2])==cursor($regsactual[2])) 
            {    
                if($regsdada[1]<$regsactual[1])
                    return true;
                else
                    return false;
            }  
            else   return false;
        }   
        else return false;    
}
/*
    esta funcion lo que hace es dado un valor de alpha,beta,rc o simplemente vacio da como 
    resultado 
*/

function cursor($valor)
{    
    if($valor=="alpha")
    {
       return 1;     
    }
    else if($valor=="beta")
    {
       return 2;     
    }
    else if($valor=="rc")
    {
       return 3;     
    }
    else if($valor=="") return 4;
} 
function imprimirArreglo($value, $version_actual,$path_folder)
{
   $update="";
   //si $value['before'] es mayor a $version_actual entra en la condicion
   //pero tambien $version_actual debe ser menor que $value['current']. 
   if(esmayor($value['current'],$version_actual)){
       $update= file_get_contents("$path_folder/update/version_sql/{$value['namefile']}");
       $update=$update."\n\n";
   }
   return  $update;    
}    
//en esta funcion hay que comprobar que la variable $version_actual tiene que tener el mismo formato 
//que los nombres de los archivos de actualizacion en la carpeta /setup/db/update. 
//
function updatedatabase($version_actual,$path_folder)
{
    $cadenareturn= "";    
    if(is_dir($path_folder."/update/version_sql"))
    {
        $directorio=dir($path_folder."/update/version_sql");
        while ($archivo = $directorio->read())
        { 
            if(is_file("$path_folder/update/version_sql/$archivo"))
            {
                if($archivo[strlen($archivo)-1]!="~" &&  $archivo[0]!="." )
                {                            
                    list($id,$before,$currentt)=split('_',$archivo);
                    list($current)=split('.sql',$currentt);
                    $arrversion=array("id"=>$id,"before"=>$before,"current"=>$current,"namefile"=>$archivo);
                    $cadenareturn .= imprimirArreglo($arrversion, $version_actual,$path_folder);      
                }
            } 
        }  
        $directorio->close();  
        return $cadenareturn;
    }
    else return null;
}
?>
