#!/usr/bin/perl -w

use DBI;
use LWP::Simple;
use Socket;

my $dbh = DBI->connect( 'dbi:mysql:dbname=lamp;host=localhost',
			'lamp', '_password_' ) or die "$DBI::errstr";

my $meq = $dbh->prepare( "select channel_number from channels where username = '';" );
$meq->execute();

socket( CLIENT, PF_UNIX, SOCK_DGRAM, 0 ) or die;
connect( CLIENT, sockaddr_un( "/tmp/lamp-display-socket" )) or die;

select CLIENT;

$|=1;

$free = 0;
while ( $channel = $meq->fetchrow_array ) {
    $free = 1;
}

if ( $free ) {
    $meq = $dbh->prepare( "select channel_number from channels where ((timeout_time < now()) and now_playing != '');" );
    $meq ->execute;
    while ( $channel = $meq->fetchrow_array ) {
	$meq = $dbh->prepare( "update channels set start_time=now(),end_time=date_add(now(),interval 80 minute),timeout_time=date_add(now(),interval 80 minute) where channel_number = $channel;" );
	$meq->execute;
	$meq = $dbh->prepare( "select unix_timestamp(timeout_time) as timeout from channels where channel_number=$channel;" );
	$meq->execute;
	($timeout) = $meq->fetchrow_array;
#	print STDERR "$channel $timeout\n";
      
	$message = pack "CCV", 3, $channel, $timeout;
	print $message;
    }
}

$meq = $dbh->prepare( "select channel_number from channels where ((username != '') and (timeout_time < now()));" );
$meq->execute;

while ( $channel = $meq->fetchrow_array ) {
    print STDERR "Killing on $channel\n";
    get("http://127.0.0.1/fake-callback.php?action=user%20time%20is%20up&channel=$channel&password=_password_");
}
