#! /usr/bin/perl

# Copyright (C) 2009-2011 Arne Wichmann
#
# This little thing is distributed under the GNU General Public License,
# version 2. If you need the license, ask your distributor for it.

# Usage: call this script in a directory containing files describing tasks
# which should be done regularly. The timestamp of these files reflects the
# last time the task was done. The first line of the file explains the
# regularity, the second line is output whenever the task should be done.
# Files are read in lexical order.
#
# Syntax of the first line is a ';'-separated sequence of t<number>, where
# number is the amount of seconds after which the task should return;
# m<number>, where number is the day of month at which this task should
# return; of w<number>, where number is the day of week at which this task
# should return. Only the last of the sequence is used. (TODO improve)
#
# After output the program waits for an answer. If the answer is yes, the
# item is considered done; if the answer is -<number>, the item is
# considered done <number> days before.

use strict;
use POSIX;

opendir(DIR,".");
my(@files)=sort grep { ! /^\./ } readdir(DIR);
closedir(DIR);

for (@files) {
  my(@stat)=stat;
  open(_);
  my(@output)=<_>;
  close(_);
  my($nexttime)=0;
  for (split(/;/,shift(@output))) { # latest is used
    my($nt);
    if (/^t(\d+)$/) { $nt=$stat[9]+$1; }
    if (/^m(\d+)$/) { # 0-30
      my(@filetime)=localtime($stat[9]);
      # TODO: buggy in december?
      $nt=POSIX::mktime(0,0,0,$1,$filetime[4]+(($filetime[3]>$1)?1:0),
        $filetime[5],0,0,-1);
    }
    if (/^w(\d)$/) { # 0-6 -> Sun-Sat
      my(@filetime)=localtime($stat[9]);
      $nt=POSIX::mktime(0,0,0,$filetime[3]+($1-$filetime[6])%7+1,
        $filetime[4],$filetime[5],0,0,-1);
    }
    $nexttime=$nt if $nt>$nexttime;
  }
  next unless $nexttime<time;
  chomp($output[$#output]);
  print @output;
  my($reply)=<STDIN>."";
  utime(undef,undef,$_) if $reply eq "y\n";
  if ($reply =~ /^\-(\d+)\n$/) { utime(undef,time()-$1*3600*24,$_); }

}

