<?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');

class Task extends Model
{
  var $Id;

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

class TaskExport extends Task
{
  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)
  {
    if (file_exists($dst)) $this->DeleteOldFiles($dst);
    if (is_dir($src)) 
    {
      if (!file_exists($dst)) mkdir($dst, 0777, true);
      $files = scandir($src);
      foreach ($files as $file)
      {
        if (($file != ".") and ($file != "..") and (!is_dir($src.'/'.$file))) 
          $this->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 mpq.exe "'.$this->GetWinZPatch($packdir.DIRECTORY_SEPARATOR.
              '..'.DIRECTORY_SEPARATOR).'patch-5.MPQ" '.$InDir.basename($File).' "'.
              $this->GetWinZPatch($packdir.DIRECTORY_SEPARATOR).$File.'" '));
          } else
          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);
    }
  }

  function ExportDBC($Task)
  {
    $Export = new Export($this->System);
    $Export->Id = $Task['ExportId'];
    $Export->Init();

    echo(date("j.n.Y H:i:s", time()).': Generování DBC souborů pro export '.$Export->Id.'.. '."\n");
    $this->SetProgress(10);

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

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

    $this->SetProgress(20);
    if (function_exists('gzcompress'))
    {
      echo(strip_tags($Export->ExportToDBC()));
      echo('Komprese...'."\n");
      $SourceDir = $Export->TempDir.'dbc/';
      if (file_exists($SourceDir))
      {
        exec('zip -r -j '.$Export->TempDir.'CzWoW_DBC.zip '.$SourceDir);
      } else echo('Directory doesn\'t exist '.$SourceDir);
      $this->SetProgress(80);
    } else echo('Funkce pro tvorbu Zip souboru není podporována!'."\n");
  }

  function ExportEXE($Task)
  {
    $Export = new ExportAddon($this->System);
    $Export->Id = $Task['ExportId'];
    $Export->Init();
    $Export->LoadFilters();

    echo(date("j.n.Y H:i:s", time()).': Generování EXE souboru pro export '.$Export->Id.'.. '."\n");
    $nsifile = 'install.nsi';

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

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

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

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

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

    $this->SetProgress(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
  }

  function Run()
  {
    global $Config;

    while (1)
    {
      $DbResult = $this->Database->query('SELECT `ExportTask`.`Id`, `ExportTask`.`Export`, '.
        '`Export`.`Id` AS `ExportId`, `Export`.`OutputType` AS `ExportOutput` FROM `ExportTask` '.
        'LEFT JOIN `Export` ON `Export`.`Id` = `ExportTask`.`Export` WHERE '.
        '(`ExportTask`.`TimeFinish` IS NULL) ORDER BY `TimeQueued`');
      while ($Task = $DbResult->fetch_assoc())
      {
        $this->Id = $Task['Id'];
        if ($Task['ExportId'] != '')
        {
          try
          {
            $this->SetProgress(0);
            $this->Database->update('ExportTask', '`Id`='.$this->Id, array('TimeStart' => 'NOW()'));

            if ($Task['ExportOutput'] == 9)
            {
              $this->ExportDBC($Task);
            } else
            if ($Task['ExportOutput'] == 10)
            {
              $this->ExportEXE($Task);
            } else echo('Unknown export output type '.$Task['ExportOutput']."\n");

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

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

$Task = new TaskExport($System);
$Task->Run();
