#!/usr/bin/perl
#

use warnings;
use strict;

use lib( '/home/perl_test' );

use DBI;
use Config;
use dbSmoke;

use constant LOGFILE => '>> /tmp/perl_test.log';

open LOG, LOGFILE;

my $dbh = DBI->connect_cached(
                               "DBI:Pg:dbname=cpan;host=chaos",
                               "",
                               "",
                               {
                                  RaiseError => 1,
                                  AutoCommit => 1,
                                  PrintError => 1
                               }
                               );

$dbh->do( "DELETE FROM processing WHERE now() - time > '1 week'" );

my $arch_index = get_arch_index( $Config{ archname }, $dbh );

my $ready_ref = $dbh->selectall_arrayref(
           qq/SELECT m.index, m.module
              FROM modules AS m
	      WHERE now() - m.time > '1 hour'
	         AND NOT EXISTS (SELECT *
				 FROM processing AS p
				 WHERE m.index = p.index)
		 AND NOT EXISTS (SELECT *
				 FROM tested AS t
				 WHERE  m.index = t.module_index
				    AND $arch_index = t.archname_index
				)/
);

foreach my $row ( @$ready_ref )
   {
   my @data = @$row;
   $dbh->do( qq/INSERT INTO processing( index ) VALUES( $data[0] )/ );
   print LOG ( join ' ', qq/cpansmoke -pas $data[1]/, "\n" );
   system qq/cpansmoke -pas $data[1]/;
   }

$dbh->disconnect;
