#!/usr/bin/perl
#
# task.autodelay  --  delay the due date of all taskwarrior tasks
#
################################################################################
#
# Copyright 2013 Andy Spiegl <task-autodelay.andy@spiegl.de>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# http://www.opensource.org/licenses/mit-license.php
#
################################################################################
#
# History:
#
# v0.1  2013-02-04: first version
# v0.2  2013-03-06: turn off stdout buffering
# v0.3  2013-03-26: added help, man page, command line options
# v0.4  2013-03-26: added new options "--quiet",  "--delay"
#
############################################

my $VERSION = "0.4";

############################################

use strict;
use warnings;

use Getopt::Long;
use Pod::Usage;

use Term::Size 'chars';


# security for shell calls:
$ENV{'PATH'} = '/bin:/usr/bin';
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

# turn off buffering (because asking questions below)
$| = 1;

############################################
# configurable VARIABLES
############################################

my $debug = 0;
my $verbose = 0;
my $nodo = 0;
my $quiet = 0;

# add 10 days to the due dates
my $delay = 10;                 # default auto-delay is 10 days


############################################
# some self detection
############################################
my $self = $0; $self =~ s|.*/||;

my $termwidth = Term::Size::chars *STDOUT{IO};
local $SIG{'WINCH'} = sub { $termwidth = Term::Size::chars *STDOUT{IO} };


############################################
# command line options
############################################
# option defaults
my $showhelp = 0;
my $showmanpage = 0;
my $showversion = 0;

GetOptions(
   'help|usage'     => \$showhelp,       # show usage
   'manpage'        => \$showmanpage,    # show manpage
   'version'        => \$showversion,    # show programm version
   'debug+'         => \$debug,          # (incremental option)
   'quiet+'         => \$quiet,          # (incremental option)
   'nodo|justprint' => \$nodo,           # just print what would have been done
   'verbose'        => \$verbose,        # show more informational messages
   'delay=s'        => \$delay,          # auto-delay in days
          ) or pod2usage(-exitstatus => 1, -verbose => 0);

$quiet = 0  if $debug;          # contradicting options

# are there more arguments?
if ($#ARGV >= 0)
{
  pod2usage(-message => "ERROR: unknown arguments \"@ARGV\".\n",
            -exitstatus => 2,
            -verbose => 0
           );
}

pod2usage(-exitstatus => 0, -verbose => 1)  if $showhelp;
pod2usage(-exitstatus => 0, -verbose => 2)  if $showmanpage;

if ($showversion)
{ print "$self - Version: $VERSION\n"; exit; }

if ($debug)
{
  print "DEBUG Mode($debug): switching $self (v$VERSION) to debug mode.\n";
}

if ($nodo)
{
  print "JUSTPRINT Mode: non-reversible actions are not performed.\n";
}


############################################
# main program
############################################
my $taskcommand;
my $task;
my $data;
my %duetasks;
my $delaytype;
my ($new_due_date, $epoch);
my $ans;
my ($delayed, $notDelayed, $autoDelayed, $autoNotDelayed, $changedToAuto, $changedToNoAuto) = (0,0,0,0,0,0);

my $delay_by_seconds = 3600*24 * $delay;

# Give a nice error if the (non-standard) JSON module is not installed.
eval "use JSON";
if ($@)
{
  print "ERROR: You need to install the JSON Perl module. (apt-get install libjson-perl)\n";
  exit 1;
}

# Use the taskwarrior export command to filter out all due tasks and return JSON
#$taskcommand = "task status:pending due.any: export";
# ignore the very old "diario" tasks:
$taskcommand = "task status:pending due.after:2012-01-01 export";

# save all due tasks into a hash
for $task (split /,$/ms, qx{$taskcommand})
{
  $data = from_json($task);
  $duetasks{ $data->{'id'} } = $data;
}

# sort by due date
foreach $task (sort { $duetasks{$a}->{'due'} cmp $duetasks{$b}->{'due'} }
               keys %duetasks)
{
  $delaytype = '';

  # are there tags for this task?
  if (exists $duetasks{$task}->{'tags'})
  {
    if (grep (/^nodelay$/, @{$duetasks{$task}->{'tags'}}) and
        grep (/^delay$/, @{$duetasks{$task}->{'tags'}}) )
    {
      print "WARNING (task $duetasks{$task}->{'id'}): tags \"nodelay\" and \"delay\" are both set.  Ignoring.\n";
      $delaytype = "ask";
    }


    # set for NO automatic delaying?
    elsif (grep (/^nodelay$/, @{$duetasks{$task}->{'tags'}}) )
    {
      $delaytype = "autonodelay";
      $notDelayed++;
      $autoNotDelayed++;
      print "VERBOSE: no auto delay -> ", $duetasks{$task}->{'uuid'} ." (". $duetasks{$task}->{'id'} .")\n"  if $verbose;
      print "Auto-NO-delaying task $duetasks{$task}->{'id'}\n"  unless $quiet;
    }


    # set for automatic delaying?
    elsif (grep (/^delay$/, @{$duetasks{$task}->{'tags'}}) )
    {
      $delaytype = "autodelay";
      print "VERBOSE: auto delay -> ", $duetasks{$task}->{'uuid'} ." (". $duetasks{$task}->{'id'} .")\n"  if $verbose;

      print "Auto-delaying task $duetasks{$task}->{'id'}\n"  unless $quiet;
      $delayed++;
      $autoDelayed++;
      &taskDelay( $duetasks{$task}->{'uuid'}, $duetasks{$task}->{'id'} );
    }

    else
    {
      # no tag names match? -> ask the user
      $delaytype = "ask";
    }
  }


  # no tags set yet? -> ask the user
  if (not $delaytype or $delaytype eq 'ask')
  {
    print `task $duetasks{$task}->{'uuid'} rc.verbose=nothing rc.defaultwidth=$termwidth`;

    $ans='';
    while ($ans !~ /^[ynANq]$/)
    {
      print "Should this task be delayed?  [(y), (n), (A)lways, (N)ever, (q)uit)]  ";
      chomp ($ans = <>);
    }

    if ($ans eq 'n')
    {
      $notDelayed++;
    }

    elsif ($ans eq 'y')
    {
      &taskDelay( $duetasks{$task}->{'uuid'}, $duetasks{$task}->{'id'} );
      $delayed++;
    }

    elsif ($ans eq 'A')
    {
      &taskSetAutoDelay( $duetasks{$task}->{'uuid'}, $duetasks{$task}->{'id'} );
      &taskDelay( $duetasks{$task}->{'uuid'}, $duetasks{$task}->{'id'} );
      $delayed++;
      $changedToAuto++;
    }

    elsif ($ans eq 'N')
    {
      &taskSetAutoNoDelay( $duetasks{$task}->{'uuid'}, $duetasks{$task}->{'id'} );
      $notDelayed++;
      $changedToNoAuto++;
    }

    elsif ($ans eq 'q')
    {
      print "STOPPED by user request.\n";
      last;
    }

  }

  print "--------------------\n";
}

print "\n\n";

if (not $quiet)
{
  print "Tasks delayed: $delayed\n";
  print "Tasks not delayed: $notDelayed\n";
  print "Tasks auto delayed: $autoDelayed\n";
  print "Tasks auto not delayed: $autoNotDelayed\n";
  print "Tasks changed to auto delay: $changedToAuto\n";
  print "Tasks changed to no auto delay: $changedToNoAuto\n";
}
exit;


sub taskDelay
{
  my ($uuid, $id) = @_;

  print "VERBOSE: Delaying task $uuid ($id) ...\n"  if $verbose;

  # get due date in epoch seconds
  $epoch = `task $uuid rc.report.all.columns:due.epoch rc.report.all.labels:DUE rc.verbose=nothing rc.color=off all`;

  $new_due_date = $epoch + $delay_by_seconds;
  print "new_due_date: $new_due_date\n"  if $debug;

  if ($nodo)
  {
    print "NODO: task $uuid modify due:$new_due_date\n";
  }
  else
  {
    print `task $uuid modify due:$new_due_date rc.verbose=nothing`;
  }
}

sub taskSetAutoDelay
{
  my ($uuid, $id) = @_;

  print "VERBOSE: Setting to auto delaying: task $uuid ($id) ...\n"  if $verbose;

  if ($nodo)
  {
    print "NODO: task $uuid modify +delay -nodelay\n";
  }
  else
  {
    print `task $uuid modify +delay -nodelay rc.verbose=nothing`;
  }
}

sub taskSetAutoNoDelay
{
  my ($uuid, $id) = @_;

  print "VERBOSE: Setting to NO auto delaying: task $uuid ($id) ...\n"  if $verbose;

  if ($nodo)
  {
    print "NODO: task $uuid modify -delay +nodelay\n";
  }
  else
  {
    print `task $uuid modify -delay +nodelay rc.verbose=nothing`;
  }
}


#----------------------------------------------------------------------------
# Doku
#----------------------------------------------------------------------------

__END__

=head1 NAME

task-autodelay  --  delay the due date of all taskwarrior tasks

=head1 SYNOPSIS

C<task-autodelay> [--help|--usage] [--version] [--manpage] [--debug] [--nodo|--justprint] [--quiet] [--verbose] [--delay <DAYS>]


=head1 DESCRIPTION

B<task-autodelay> loops through all taskwarrior tasks with a due date.

- If task has tag "delay"  ->  given delay (10 days by default) are added to due date
- If task has tag "nodelay"  ->  nothing happens with this task
- Otherwise user is asked what to do

The user can see what's being done.  Use option B<--quiet> to suppress messages.

To see more verbosely what happens: use option B<--verbose>
To safely try out the script: use option B<--nodo>


=head1 OPTIONS

All options can be shortened with their first (unique) characters.

=over 3

=item B<--delay DAYS>

set the number of days for delaying tasks.  Default is 10 days.

=item B<--quiet>

show less informational messages (can be used multiple times to show even less)

=item B<--verbose>

show more informational messages about what's being done

=item B<--nodo>, B<--justprint>

don't really execute anything, just print what would've been done

=item B<--debug>

show debug messages (can be used multiple times to increase the debug level)

=item B<--help>, B<--usage>

show command syntax

=item B<--manpage>

show complete manpage

=item B<--version>

show program version


=head1 DOWNLOAD

 http://spiegl.de/andy/software/task-autodelay.pl

 Details and discussion: http://taskwarrior.org/boards/1/topics/2767

=head1 EXAMPLES

  $ task-autodelay --delay 14


=head1 EXITCODES

B<0>  everything okay

Any other exitcode means something has gone wrong.


=head1 LEGALESE

Copyright 2013 Andy Spiegl <task-autodelay.andy@spiegl.de>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

http://www.opensource.org/licenses/mit-license.php

=head1 AUTHOR

Dr. Andy Spiegl E<lt>task-autodelay.andy@spiegl.deE<gt>

=cut
