<?php

ini_set('memory_limit', '100M');

include_once(dirname(__FILE__).'/../../includes/global.php');
include_once(dirname(__FILE__).'/../../includes/zip.lib.php');

include_once('Export.php');
include_once('ExportOutput.php');

//LoadCommandLineParameters();
$System = new Core();
$System->DoNotShowPage = true;
$System->Run();

function SetProgress($Export, $Progress)
{
   global $System;

   $System->Database->query('UPDATE `ExportTask` SET `Progress`='.$Progress.' WHERE `Export`='.$Export->Id);
}

function DeleteOldFiles($deldir)
{
  if(file_exists($deldir.'/'))
  {
    $Dir = opendir($deldir.'/') ;
    while(($File = readdir($Dir)) !== false)
    {
      if(($File != '..') and ($File != '.') and (!is_dir("$File"))) unlink($deldir.'/'.$File);
    }
    closedir($Dir);
  }
}

function rcopy($src, $dst)
{
 // echo  $src.' '.$dst."\n";
  if (file_exists($dst)) DeleteOldFiles($dst);
  if (is_dir($src)) {
    if (!file_exists($dst)) mkdir($dst, 0777, true);
    $files = scandir($src);
    foreach ($files as $file)
    if ($file != "." && $file != ".." and (!is_dir("$src/$file"))) rcopy("$src/$file", "$dst/$file");
  }
  else if (file_exists($src)) copy($src, $dst);
}

function GetWinZPatch($patch)
{
  //TMP="Z:\\a\\www\\wowpreklad\\tmp\\Export\\${EXPORTID}\\"
  $patch = str_replace(DIRECTORY_SEPARATOR,'\\',$patch);
  $patch = 'Z:'.$patch;
  return $patch;
}

function MPQPack($packdir)
{
  if(file_exists($packdir.DIRECTORY_SEPARATOR))
  {
    $Dir = opendir($packdir.DIRECTORY_SEPARATOR) ;
    while(($File = readdir($Dir)) !== false)
    {
      if(($File != '..') and ($File != '.')) {
        $File = str_replace('/',DIRECTORY_SEPARATOR,$File);
        $InDir = '';
        if (strpos($packdir,'dbc') !== false) {
          $InDir = 'DBFilesClient\\';
          if (DIRECTORY_SEPARATOR == '/') // linux
            $InDir = 'DBFilesClient\\\\';
        }
        if (strpos($packdir.$File,'luaGlobal') !== false) {
          $InDir = 'Interface\\FrameXML\\';
          if (DIRECTORY_SEPARATOR == '/') // linux
            $InDir = 'Interface\\\\FrameXML\\\\';
        }
        if (strpos($packdir.$File,'luaGlue') !== false) {
          $InDir = 'Interface\\GlueXML\\';
          if (DIRECTORY_SEPARATOR == '/') // linux
            $InDir = 'Interface\\\\GlueXML\\\\';
        }

        if (DIRECTORY_SEPARATOR == '/') // linux
          echo exec('wine cmd /C mpq.exe "'.GetWinZPatch($packdir.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR).'patch-5.MPQ" '.$InDir.basename($File).' "'.GetWinZPatch($packdir.DIRECTORY_SEPARATOR).$File.'" ');

        if (DIRECTORY_SEPARATOR == '\\') // windows
          echo exec('mpq.exe "'.$packdir.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'patch-5.MPQ" '.$InDir.basename($File).' "'.$packdir.DIRECTORY_SEPARATOR.$File.'" ');

        echo "\n";
      }
    }
    closedir($Dir);
  }
}

while(1)
{
  // DBC files
  $DbResult = $System->Database->query('SELECT `ExportTask`.`Export`, `Export`.`Id` AS `ExportId` FROM `ExportTask`'.
    ' LEFT JOIN `Export` ON `Export`.`Id` = `ExportTask`.`Export` WHERE `Export`.`OutputType` = 9 AND `ExportTask`.`TimeFinish` IS NULL');
  while($DbRow = $DbResult->fetch_assoc())
  {
    echo(StrFTime("%d/%m/%Y %H:%M:%S", time()).': Generování DBC souborů pro export '.$DbRow['ExportId'].'.. '."\n");
    if($DbRow['ExportId'] != '')
    {
      try
      {
        $Export = new Export($System);
        $Export->Id = $DbRow['ExportId'];
        $Export->Init();

        SetProgress($Export,10);

        echo('Mazání starých souborů...'."\n");

        // Delete old files
        DeleteOldFiles($Export->TempDir.'dbc');
        if(file_exists($Export->TempDir.'CzWoW_DBC.zip')) unlink($Export->TempDir.'CzWoW_DBC.zip');

        SetProgress($Export,20);
        if(function_exists('gzcompress'))
        {
          $Export->ExportToDBC();
          echo('Komprese...'."\n");
          exec('zip -r -j '.$Export->TempDir.'CzWoW_DBC.zip '.$Export->TempDir.'dbc/');
          echo('Hotovo'."\n");
          SetProgress($Export,80);
        } else echo('Funkce pro tvorbu Zip souboru není podporována!'."\n");
        $System->Database->query('UPDATE `ExportTask` SET `TimeFinish`=NOW() WHERE `Export`='.$Export->Id);
      } catch (Exception $e)
      {
        echo 'Caught exception: ',  $e->getMessage(), "\n";
      }
      SetProgress($Export,100);
    } else
    {
      $System->Database->query('DELETE FROM `ExportTask` WHERE `Export`='.$DbRow['Export']);
      echo('Export '.$DbRow['Export'].' nenalezen. Jeho úloha smazána.'."\n");
    }
  }

  //EXE files
  $DbResult = $System->Database->query('SELECT `ExportTask`.`Export`, `Export`.`Id` AS `ExportId` FROM `ExportTask`'.
    ' LEFT JOIN `Export` ON `Export`.`Id` = `ExportTask`.`Export` WHERE `Export`.`OutputType` = 10 AND `ExportTask`.`TimeFinish` IS NULL');
  while($DbRow = $DbResult->fetch_assoc())
  {
    echo(StrFTime("%d/%m/%Y %H:%M:%S", time()).': Generování EXE souboru pro export '.$DbRow['ExportId'].'.. '."\n");
    if($DbRow['ExportId'] != '')
    {
      try
      {
     // echo shell_exec('"'.dirname(__FILE__).'./client_cz_export.sh" '.$DbRow['ExportId'].'');


        $Export = new ExportAddon($System);
        $Export->Id = $DbRow['ExportId'];
        $Export->Init();
        $Export->LoadFilters();

        $nsifile = 'install.nsi';

        // Delete old files
        SetProgress($Export,1);
        echo('Delete old files...'."\n");
        DeleteOldFiles($Export->TempDir.'dbc');
        DeleteOldFiles($Export->TempDir.'lua');
        DeleteOldFiles($Export->TempDir.'CzWoW');

        //copy need files
        SetProgress($Export,5);
        echo('Copy files...'."\n");
        rcopy('files/'.$Export->ClientVersion['Version'].'/patch-5.MPQ', $Export->TempDir.'patch-5.MPQ');
        rcopy('files/'.$Export->ClientVersion['Version'].'/'.$nsifile, $Export->TempDir.$nsifile);
        rcopy('files/'.$Export->ClientVersion['Version'].'/WowLua.exe', $Export->TempDir.'WowLua.exe');
        rcopy('files/'.$Export->ClientVersion['Version'].'/CzWoW/', $Export->TempDir.'CzWoW/');
        rcopy('files/WoW.ico', $Export->TempDir.'WoW.ico');
        rcopy('files/Fonts/', $Export->TempDir.'Fonts/');

        SetProgress($Export,10);
        echo('Export lua...'."\n");
        $Export->ExportToLua();
        SetProgress($Export,15);
        echo('Export CzWoW...'."\n");
        $Export->MakeAddon();
        SetProgress($Export,30);
        echo('Export dbc...'."\n");
        $Export->ExportToDBC();

        echo('Create readme...'."\n");
        SetProgress($Export,60);
        $File = new FileStream();
        $File->CreateFile($Export->TempDir.'ReadMe.htm');
        $File->WriteLine($Export->GetReadme());
        unset($File);

        echo('Packing files...'."\n");
        SetProgress($Export,70);
        $workdir = str_replace('/',DIRECTORY_SEPARATOR,$Export->TempDir);
        MPQPack($workdir.'lua');
        SetProgress($Export,80);
        MPQPack($workdir.'dbc');

        SetProgress($Export,90);
        echo('Creating instalator...'."\n");
        if (DIRECTORY_SEPARATOR == '/') // linux
          echo exec('makensis '.$workdir.$nsifile);

        if (DIRECTORY_SEPARATOR == '\\') // windows
          echo exec('"'.$workdir.$nsifile.'" '); //"c:\Program Files (x86)\NSIS\makensisw.exe" /Xscriptcmd

        SetProgress($Export,100);
        echo ("\n"."Hotovo"."\n");
        $System->Database->query('UPDATE `ExportTask` SET `TimeFinish`=NOW() WHERE `Export`='.$DbRow['Export']);
      } catch (Exception $e)
      {
        echo 'Caught exception: ',  $e->getMessage(), "\n";
      }
    } else
    {
      $System->Database->query('DELETE FROM `ExportTask` WHERE `Export`='.$DbRow['Export']);
      echo('Export '.$DbRow['Export'].' nenalezen. Jeho úloha smazána.'."\n");
    }
  }
  sleep($Config['ExportTaskProcessPeriod']);
}

//  WriteLog('Generování dbc úloh', LOG_TYPE_DOWNLOAD);
