<?php
$MangosUptimeInterval = 60; // Matches UpdateUptimeInterval in mangosd.conf [seconds]
$RestartDeadTime = 3 * 60; // Maximum dead time [seconds]
$LoopSleepTime = 10; // Checking period [seconds]
$MangosProcessName = '/a/mangos1/bin/mangos-worldd';

include('../global.php');

echo('MaNGOS freeze restarter. Checking DB every '.$LoopSleepTime." seconds\n");
$Restarted = 0;
$Database->select_db('realm1_mangos');
while(1)
{
  $DbResult = $Database->query('SELECT `starttime`, `uptime` FROM `uptime` ORDER BY `starttime` DESC LIMIT 1');
  $DbRow = $DbResult->fetch_array();
  $DbUptime = $DbRow['uptime'];
  $RealUptime = time() - $DbRow['starttime']; 
  $TimeDifference = $RealUptime - $DbUptime;
  echo('Uptime DB: '.$DbUptime.' vs. Real: '.$RealUptime." [s],  Restart condition ".$TimeDifference." > ".$RestartDeadTime.
    " (".round($TimeDifference / $RestartDeadTime * 100)."%)\n");
  if($TimeDifference > $RestartDeadTime)
  {
    if($Restarted == 0) 
    {
      echo("Restarting MaNGOS...\n");
      exec("ps -ef | grep '".$MangosProcessName."' | grep -v grep | awk '{print $2}' | xargs -i kill {}");
      $Restarted = 1;  // Restart only once and wait for new good uptime
      echo("Waiting for new good uptime...\n");
    }
  } else 
  {
    if($Restarted == 1)
    {
      echo("MaNGOS is back online.\n");
      $Restarted = 0;
    }
  }
  Sleep($LoopSleepTime);
}

?>