#!/usr/bin/perl
#Copyright (c) 2008, Zane C. Bowers
#All rights reserved.
#
#Redistribution and use in source and binary forms, with or without modification,
#are permitted provided that the following conditions are met:
#
#   * Redistributions of source code must retain the above copyright notice,
#    this list of conditions and the following disclaimer.
#   * Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
#ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
#WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
#IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
#INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
#BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
#DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
#LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
#OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
#THE POSSIBILITY OF SUCH DAMAGE.

use DateTime::Event::Cron;
use DateTime::Duration;
use DateTime::Format::Strptime;
use strict;
use warnings;
use Getopt::Std;
use ZConf;

$Getopt::Std::STANDARD_HELP_VERSION = 1;

#version function
sub main::VERSION_MESSAGE {
	print "zccron 0.0.1\n";
};

#print help
sub main::HELP_MESSAGE {
	print "\n".
		"-s <zconf set>  The zconf set to use.\n".
		"-t <tab>  The tab to use.\n";
}

#takes a cronline and runs it if it is with within a minute and 15 seconds of last and next
sub run_cron_line{
	my $cronline = $_[0];
	my $now=DateTime->now;#get the time

	my $dtc = DateTime::Event::Cron->new_from_cron($cronline);
	my $next_datetime_string = $dtc->next;
	my $last_datetime_string = $dtc->previous;

	#takes the strings and make DateTime objects out of them.
	my $time_string_parse= new DateTime::Format::Strptime(pattern=>'%FT%T');
	my $dt_last=$time_string_parse->parse_datetime($last_datetime_string);
	my $dt_next=$time_string_parse->parse_datetime($next_datetime_string);

	#check to make sure last or next is within a minute and 15 seconds of now.
	my $interval = DateTime::Duration->new(minutes => 1);

	#if it falls within 1 minute and 15 secons of now, it runs it
	if (within_interval($dt_last, $now, $interval) || within_interval($dt_next, $now, $interval)){		
		system($dtc->command());
	}
}

# within_interval is copied from http://datetime.perl.org/index.cgi?FAQSampleCalculations
sub within_interval {
    my ($dt1, $dt2, $interval) = @_;

    # Make sure $dt1 is less than $dt2
    ($dt1, $dt2) = ($dt2, $dt1) if $dt1 > $dt2;

    # If the older date is more recent than the newer date once we
    # subtract the interval then the dates are closer than the
    # interval
    if ($dt2 - $interval < $dt1) {
        return 1;
    } else {
        return 0;
    };
}

#gets the options
my %opts=();
getopts('s:t:', \%opts);

if (!defined($opts{t})) {
	$opts{t}="default";
}

#inits zconf
my $zconf = ZConf->new();
if($zconf->{error}){
	warn("zccron:1: Could not initiate ZConf. It failed with '".$zconf->{error}."'".
		", '".$zconf->{errorString}."'");
	exit 1;
}

#handles set checking
if(defined($opts{s})){
	if(!$zconf->setNameLegit($opts{s})){
		warn("zccron:2: '".$opts{s}."' is not a legit ZConf set name");
		exit 2;
	}
}else{
	$opts{s}=undef;
}

#exit if the config does not exist
my $returned = $zconf->configExists("zccron");
if (!$returned) {
	warn("zccron:3: The config 'zccron' does not exist. Please use zccrontab(1)".
		 "to create it");
	exit 3;
}

#read the config
$returned = $zconf->read({config=>"zccron", set=>$opts{s}});
if($zconf->{error}){
	warn("zccron:4: Could not read config. It failed with '".$zconf->{error}."'".
		", '".$zconf->{errorString}."'.");
	exit 4;
}

my $tab='tabs/'.$opts{t};

#runs the tab if it exists and exits if it does not
if (defined($zconf->{conf}{zccron}{$tab})){
	#splits the lines apart
	my @lines=split(/\n/, $zconf->{conf}{zccron}{$tab});

	#runs each line
	my $linesInt=0;
	while (defined($lines[$linesInt])){
		if (!($lines[$linesInt] =~ /^#/)){
			run_cron_line($lines[$linesInt]);
		}

		$linesInt++;
	}
	
}else{
	warn("zccron:5: The specified tab, '".$opts{t}."', does not exist");
	exit 5;
}

=head1 NAME

comiccron - A cron like tool largely aimed at bringing up my web comics in the
morning with a single command.

=head1 SYNOPSIS

comiccron [B<-s> <ZConf set>] -f <tab>

=head1 USAGE

This will act on any cronfile it is pointed at. For it to run the command, the
last or next time it will be will have to be within a minute. For most usages,
you will want to have the hour and minute set to *. This allows a user to do
something how ever many times they want any time during the period it is active.

After running through every entry in the crontab, it then exits.

You need to use the full path for specifying the command.

=head1 WHY NOT CRON

You can have cron open opera or the like on a specific display by either switch
or enviromental options, but it will always open it. This allows you to open it
any time along the point it is active.

=head1 ZConf Keys

The keys for this are stored in the config 'zccron'.

=head2 tabs/<tab>

Any thing under tabs is considered a tab.

=head1 ERROR CODES

=head2 1

ZConf initialization error.

=head2 2

The specified set is not a legit ZConf set name.

=head2 3

The specified config config does not exist. Please use zccrontab(1) to create
it.

=head2 4

Reading the config 'zccron' failed.

=head2 5

The specified tab does not exist.

=head1 AUTHOR

Copyright (c) 2008, Zame C. Bowers <vvelox@vvelox.net>

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS` OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=head1 Changelog

=head2 2008-06-24/17:30

Fix issue with it not skipping things with /^#/.

=head2 2008-06-23/15:30

Initial release.

=head1 SCRIPT CATEGORIES

Desktop

=head1 OSNAMES

any

=head1 README

zccron - A single pass cron that uses ZConf as a backend.

=cut