#!/usr/bin/perl
#
# Datetime external ACL for Squid
#
# Takes a filename as an argument. The file should contain one
# datetime argument per line in the format "format value". The
# format is as per the unix strftime format. If the current
# datetime matches the value on the line in the right format,
# then "OK" is returned, otherwise "ERR" is returned.
#
# Example 1 (matches Tuesday or Wednesday):
# %u 2
# %u 3
# 
# Example 2 (matches February):
# %m 02
#
# See "man strftime" for a list of formats
#

use strict;
use POSIX qw( strftime );

$|=1;

if ( @ARGV != 1 ) {
    print STDERR "Usage: $0 date_time_file\n";
    exit 1
}

my $date_time_file = shift @ARGV;
my $file_mod_previous;
my @lines;

open FILE, $date_time_file or die "Unable to open paramter file: $date_time_file";

QUERY: while(<>) {

    my @stats = stat FILE;
    if ($file_mod_previous != $stats[9]) {
        # File changed. Re-read.
        seek( FILE,0,0 );
        @lines = <FILE>;
    }
    $file_mod_previous = $stats[9];

    foreach my $line ( @lines ) {
        my ($start_format, $start_time) = split(/[\s\n]+/, $line);
        if (!$start_format || !$start_time) {
            chomp($line);
            print "ERR Invalid input line \"$line\" in file $date_time_file. Format should be \"time_format time\".\n";
            next QUERY;
        }

        my $curday = strftime($start_format, localtime);

        if ( $curday == $start_time ) {
            print "OK\n";
            next QUERY;
        }
    }
    print "ERR\n";

}

close FILE;
