#!/usr/bin/perl

use strict;
use lib '/home/oc/cgi-bin/poll/';
use Poll;
use Mail::Sender;

my $POLLPATH='/home/oc/cgi-bin/poll/data'; 


sub Send_Mail {
    my $sender=new Mail::Sender{
        smtp=>'localhost',
        from=>'Opinion Poll Cron <webmaster@opencores.org>',
        to=>'Webmaster <webmaster@opencores.org>',
        subject=>$_[0],
    };
    $sender->MailMsg({msg=>$_[1]});
}

sub Date_To_Str {
    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
    $year+=1900;
    $mon+=1;
    foreach ($mday,$mon) {
        $_='0'.$_ if (length($_)<2);
    }
    return "$year$mon$mday";
}

sub Main {
    my $poll=new WWW::Poll;
    $poll->path($POLLPATH);
    my %polls=$poll->list;
    my $pollid=$poll->get();
    my $new_pollid=$pollid;
    foreach (keys %polls) {
        if ($_>$pollid && ($_<$new_pollid || $pollid==$new_pollid)) {
            $new_pollid=$_;
        }
    }
    print "Current poll: $pollid\nNext poll: $new_pollid\n";
    if ($new_pollid!=$pollid) {
        `echo -n "$new_pollid" > $POLLPATH/qid.dat`;
	`chown oc.users $POLLPATH/qid.dat`;
        open(SOURCE,"$POLLPATH/questions.dat");
        open(DEST,">$POLLPATH/questions.dat.new");
        while (my $line=<SOURCE>) {
            my @item=split(/\t/,$line);
            if ($item[0] eq $new_pollid) {
                $item[1]=Date_To_Str;
            }
            print DEST join("\t",@item);
        }
        close(SOURCE);
        close(DEST);
        `mv $POLLPATH/questions.dat.new $POLLPATH/questions.dat`;
        `chown oc.users $POLLPATH/questions.dat`;
    } else {
        Send_Mail('Please add some opinion polls',
        'We are already at last opinion poll and I cannot set next one for current.'.
        "\n".'You have to add some polls and set current poll manualy.'."\n\n".
        'Opinion Poll Cron');
    }
}

Main;
