<?php

/**
* This is a simple script to shutdown a frontend when it is ideling in the mainmenu
* I wrote this because i want to shutdown my frontent when the timer i can set in mythtv was reached and returned to the main menu
*/

$host = "192.168.0.25";
$port = 6546;
$socketTimeOut = 30;
$idleMenuSecs = 300;
$shutDownProgramm = "sudo /sbin/halt";

// try to open the socket 
$fp = false;
while($fp == false) {
 $fp=@fsockopen($host,$port, $errno, $errstr, $socketTimeOut);
 sleep(5);
}

// read the menu :)
readTerminal(&$fp,$bla='');

echo "Connected to the server: ".$host.":".$port."\n";

// start the loop here :)
readMenuStatus(&$fp,&$idleMenuSecs);

// loop exit ? well call the shutdown command :)
$ls = system($shutDownProgramm);
die();


/**
* This looks at the status of the menu
*/
function readMenuStatus(&$fp,&$idleMenuSecs,&$inMainMenu = false) {

  echo "Sending command: query location\n";

  $status = '';
  sendCommand(&$fp,'query location',&$status);
  echo "Current Menu is: ".$status."\n";

  // we are in the mainmenu 
  if(strpos($status,"mainmenu") !== false) {
    if($inMainMenu == false) {
      // first time in mainmenu
      echo "In mainmenu, next time i will shutdown the system\n"; 
      $inMainMenu = true;
    } else {
      // still in mainmenu ? call shutdown
      echo "Shutting down system !\n"; 
      fclose($fp);
      return;
    } 
  } else {
   $inMainMenu = false;
  }

  sleep($idleMenuSecs);

  readMenuStatus(&$fp,&$idleMenuSecs,&$inMainMenu);
}


/**
* reads data from the terminal
*/
function readTerminal(&$fp,&$r) {

  $r='';
  do { 
    $r.=fread($fp,1000);
    $s=socket_get_status($fp);
  } while ($s['unread_bytes']);
}

/**
* sends command to the terminal
*/
function sendCommand(&$fp,$c,&$r) {
  if ($fp) {
    fputs($fp,"$c\r");
    fputs($fp,"\n");
    sleep(1);
    readTerminal(&$fp,&$r);
    $r=preg_replace("/^.*?\n(.*)\n[^\n]*$/","$1",$r);
  }
  return $fp?1:0;
}

?>
