<?php

### COPYRIGHT (c)2006 Ben Isaacs (XO)

### APPLICATION: Watchdog
###     VERSION: 0.2 
###     HISTORY: 2006-04-08 Initial Version
###            0.2: 2006-04-25 Made it more portable.

/************************************************************************
This program is freeware, and may be modified or redistributed in any way.
It comes with ABSOLUTELY NO WARRANTY of any kind, express or implied, 
including the assumption of fitness for any purpose. Use at your own risk.

Author: Ben Isaacs http://www.ben-xo.com/

Usage:
1) modify the config below for your web server
2) add a line to crontab something like

    * * * * * (cd /where/ever/; php watchdog.php)

3) touch /tmp/.xo.watchdog 

  (otherwise the first time it runs, it'll think apache's crashed and 
   restart it nastily.)

************************************************************************/

/** config **/

define('WATCHED_WEBSITE''http://www.ben-xo.com/');
define('NOTIFICATION_EMAIL''watchdog@ben-xo.com');

// these are for Gentoo
$restart_commands = array(
    
'killall -9 apache2',
    
'/etc/init.d/apache2 zap',
    
'/etc/init.d/apache2 start'
);

/***********************************************************************/

if(!file_exists('/tmp/.xo.watchdog')) {
    
// previous watchdog must have timed out
    
watchdog_restart();
    
touch('/tmp/.xo.watchdog');
    exit();
} else {
    
unlink("/tmp/.xo.watchdog");
}

// if the connection below hangs, then the script will time out after 15 seconds
// leaving the flag file deleted. next time this script is run, it will detect
// the time-out, using the block above.

set_time_limit(15); // seconds
$page file(WATCHED_WEBSITE); 

if(empty(
$page)) {
    
watchdog_restart();
}
touch('/tmp/.xo.watchdog');

function 
watchdog_restart() {
    global 
$restart_commands;

    foreach (
$restart_commands as $c) {
        
system($c);
    }

    
mail(NOTIFICATION_EMAIL'Watchdog @ '.date('r'), 'restarted apache watching '.WATCHED_WEBSITE);
}

?>