<?php

include_once(dirname(__FILE__).'/../../Base/Model.php');

class MangosDebug extends Model
{
  var $ItemPerPage = 35;
  var $MaxMangosThreadCount = 12;
  
  function __construct($System)
  {
    parent::__construct($System);
  } 
  
  function ProcessLog($RealmId)
  {
    $Output = '';
    // Read server Id from first parameter
    $Realm = new Realm($this->System, $RealmId);
    
    $LogDir = '../realm/'.$RealmId.'/log/';
    $MangosConfFile = '../realm/'.$RealmId.'/etc/mangosd.conf';
    $StdOutLogFile = $LogDir.'mangos-worldd.log';
    $ErrOutLogFile = $LogDir.'mangos-worldd.err';
    $MangosLogFile = $LogDir.'Server.log';
    $MangosDbErrorsLogFile = $LogDir.'DBErrors.log';

    if(!file_exists($StdOutLogFile)) exit;
    
    $Content = file_get_contents($StdOutLogFile);
    $Lines = explode("\n", $Content);
    $Content = ''; // Free unused memory

    // Separate information from log file
    $Line = 0;
    while(($Line < count($Lines)) and (substr($Lines[$Line], 0, 6) != 'MaNGOS')) $Line++;
    $MangosVersion = $Lines[$Line];

    // Try to find start of backtrace
    while(($Line < count($Lines)) and (substr($Lines[$Line], 0, 16) != 'Program received')) $Line++;
    $Backtrace = array_slice($Lines, $Line, count($Lines) - $Line);   // Assume rest of file to be backtrace
    $Backtrace = addslashes(implode("\n", $Backtrace));
    $Lines = '';

    //$Log = array_slice($Lines, 0, $Line);
    //$Log = addslashes(implode("\n", $Log));
  
    // Get used database version from database
    $DbResult = $this->Database->query('SELECT * FROM `realm'.$RealmId.'_mangos`.`db_version`');
    $DbRow = $DbResult->fetch_array();
    $DbVersion = $DbRow['version'];
    
    // Get last uptime info
    $DbResult = $this->Database->query('SELECT * FROM `server'.$Realm->Data['Server'].'_realmd`.`uptime` ORDER BY `starttime` DESC LIMIT 1');
    //$Output = $this->Database->error;
    $DbRow = $DbResult->fetch_array();
    $MaxPlayerCount = $DbRow['maxplayers'];
    $Uptime = $DbRow['uptime'];

    // Insert data to database
    $this->Database->query('INSERT INTO `Debug` (`Realm`, `Time`, `MangosVersion`, `DbVersion`, `Uptime`, `MaxPlayerCount`) VALUES ('.$RealmId.', NOW(), "'.$MangosVersion.'", "'.$DbVersion.'", '.$Uptime.', '.$MaxPlayerCount.')');
    $InsertId = $this->Database->insert_id;

    // Insert data in separate query to partly avoid too long query packet error
    $this->Database->query('UPDATE `Debug` SET Backtrace="'.$Backtrace.'" WHERE Id='.$InsertId);
    $Backtrace = '';
    
    if(file_exists($MangosLogFile))
    {
      $Log = addslashes(file_get_contents($MangosLogFile));
      $this->Database->query('UPDATE `Debug` SET Log="'.$Log.'" WHERE Id='.$InsertId);
      unlink($MangosLogFile);
    }
    
    if(file_exists($MangosDbErrorsLogFile))
    {
      $Log = addslashes(file_get_contents($MangosDbErrorsLogFile));
      $this->Database->query('UPDATE `Debug` SET DbErrors="'.$Log.'" WHERE Id='.$InsertId);
      unlink($MangosDbErrorsLogFile);
    }

    if(file_exists($MangosConfFile))
    {
      $Configuration = array();
      $Log = addslashes(file_get_contents($MangosConfFile));
      $LogLines = explode("\n", $Log);
      foreach($LogLines as $LogLine)
      {
        if(substr($LogLine, 0, 1) != '#') $Configuration[] = $LogLine;
      }
      $this->Database->query('UPDATE `Debug` SET Configuration="'.implode("\n", $Configuration).'" WHERE Id='.$InsertId);
    }

    if(file_exists($ErrOutLogFile))
    {
      $Log = addslashes(file_get_contents($ErrOutLogFile));
      $this->Database->query('UPDATE `Debug` SET ErrorLog="'.$Log.'" WHERE Id='.$InsertId);
      unlink($ErrOutLogFile);
    }
    unlink($StdOutLogFile);
    return($Output);
  }
}
