#!@PERL@
# BEGIN BPS TAGGED BLOCK {{{
#
# COPYRIGHT:
#
# This software is Copyright (c) 1996-2024 Best Practical Solutions, LLC
#                                          <sales@bestpractical.com>
#
# (Except where explicitly superseded by other copyright notices)
#
#
# LICENSE:
#
# This work is made available to you under the terms of Version 2 of
# the GNU General Public License. A copy of that license should have
# been provided with this software, but in any event can be snarfed
# from www.gnu.org.
#
# This work is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 or visit their web page on the internet at
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
#
#
# CONTRIBUTION SUBMISSION POLICY:
#
# (The following paragraph is not intended to limit the rights granted
# to you to modify and distribute this software under the terms of
# the GNU General Public License and is only of importance to you if
# you choose to contribute your changes and enhancements to the
# community by submitting them to Best Practical Solutions, LLC.)
#
# By intentionally submitting any modifications, corrections or
# derivatives to this work, or any other work intended for use with
# Request Tracker, to Best Practical Solutions, LLC, you confirm that
# you are the copyright holder for those contributions and you grant
# Best Practical Solutions,  LLC a nonexclusive, worldwide, irrevocable,
# royalty-free, perpetual, license to use, copy, create derivative
# works based on those contributions, and sublicense and distribute
# those contributions and any derivatives thereof.
#
# END BPS TAGGED BLOCK }}}
use strict;
use warnings;

# fix lib paths, some may be relative
BEGIN { # BEGIN RT CMD BOILERPLATE
    require File::Spec;
    require Cwd;
    my @libs = ("@RT_LIB_PATH@", "@LOCAL_LIB_PATH@");
    my $bin_path;

    for my $lib (@libs) {
        unless ( File::Spec->file_name_is_absolute($lib) ) {
            $bin_path ||= ( File::Spec->splitpath(Cwd::abs_path(__FILE__)) )[1];
            $lib = File::Spec->catfile( $bin_path, File::Spec->updir, $lib );
        }
        unshift @INC, $lib;
    }

}

use RT::Interface::CLI qw(Init);
my %opt;
Init(\%opt, 'older=s', 'verbose');

$opt{'older'} ||= '1M';
unless ( $opt{'older'} =~ /^\s*([0-9]+)\s*(H|D|M|Y)?$/i ) {
    print STDERR "Incorrect format used for the 'older' argument\n";
    exit(1);
}
my ( $num, $unit ) = ( $1, uc( $2 || 'D' ) );
my %factor = ( H => 60 * 60 );
$factor{'D'}  = $factor{'H'} * 24;
$factor{'M'}  = $factor{'D'} * 31;
$factor{'Y'}  = $factor{'D'} * 365;
$opt{'older'} = $num * $factor{$unit};

if ( $opt{'older'} < 7*3600*24 ) {
    print STDERR "The 'older' argument should be greater than 7 days to avoid removing deferred email before it is sent\n";
    exit(1);
}

if ( $opt{'verbose'} ) {
    print "Running...\n";
}

require POSIX;
my $date = POSIX::strftime("%Y-%m-%d %H:%M", gmtime( time - $opt{'older'} ) );

my $dbh = RT->DatabaseHandle->dbh;
my $sth = $dbh->prepare("DELETE FROM Attributes WHERE Name='DeferredRecipients' AND Created < ?");
die "Couldn't prepare query: ". $dbh->errstr unless $sth;
my $rows = $sth->execute( $date );
die "Couldn't execute query: ". $dbh->errstr unless defined $rows;

RT->Logger->info("Successfully deleted $rows DeferredRecipients attributes") if $rows > 0;

if ( $opt{'verbose'} ) {
    if ( $rows > 0 ) {
        print "Successfully deleted $rows DeferredRecipients attributes";
    }
    else {
        print "No rows to delete\n";
    }
}

__END__

=head1 NAME

rt-clean-attributes - clean obsolete RT attributes

=head1 SYNOPSIS

     rt-clean-attributes
     rt-clean-attributes --older 1M

=head1 DESCRIPTION

This script deletes obsolete C<DeferredRecipients> attributes.

C<DeferredRecipients> attributes are used by L<rt-email-digest> to store
email to be sent at a later time, either daily or weekly. Since
L<rt-email-digest> processes transactions created at most one week in
the past, it's safe to delete C<DeferredRecipients> attributes older than
one week since they will never be accessed.

=head1 OPTIONS

=over 4

=item C<--older>

Date interval in the C<< <NUM>[<unit>] >> format. Default unit is D(ays),
H(our), M(onth) and Y(ear) are also supported.

=item C<--verbose>

Show additional output on the command line when running.

=back

=cut
