#!perl

=head1 NAME

file_cleaner_by_du - Removes files based on disk space usage till it drops below the specified amount.

=head1 SYNOPSIS

file_cleaner_by_du B<-p> <path> B<-d> <du> [B<-m> <min_files>] [B<--pretty>] [B<--dry_run>]

=head1 DESCRIPTION

This works via doing the following.

1: Check if disk usage is above the specified threshold. If not it ends here.

2: Search for files under the specified path.

3: If the number of found files is less than the number of files to keep regardless
of disk size it ends here. So if min_files is set to 32 and there are only 3 files,
then it would just return.

4: Get the stats for all the found files.

5: If min_files is specified, remove that many of the files from the list, starting
with the newest.

6: Removes the oldest file.

7: Check disk usage again and if it is less it ends here.

8: Go back to 6.

The results are then printed as JSON. To find information on the keys, please
see L<App::FileCleanerByDiskUage>.

If there were no errors, it will exit zero.

=head1 FLAGS

=head2 -d <du>

Target disk usage.

=head2 -p <path>

The path to operate on.

=head2 --dry_run

Do not actually delete anything. Instead just check if what it would delete
is writable by the current user.

=head2 -i <regex>

Optional ignore regex.

=head2 -i <min files>

Optional minimum number of files to keep regardless of disk usage.

=head2 --pretty

Pretty print the results.

=head2 -v | -version

Print version.

=head2 -h | --help

Print help,

=cut

use strict;
use warnings;
use Getopt::Long qw(:config pass_through);
use JSON;
use App::FileCleanerByDiskUage;

sub version {
	print "file_cleaner_by_du v. 0.0.1\n";
}

my $help;
my $version;
my $du;
my $path;
my $ignore;
my $min_files;
my $pretty;
my $dry_run;
GetOptions(
	'd=s'     => \$du,
	'p=s'     => \$path,
	'i=s'     => \$ignore,
	'm=s'     => \$min_files,
	'help'    => \$help,
	'h'       => \$help,
	'version' => \$version,
	'v'       => \$version,
	'pretty'  => \$pretty,
	'dry_run' => \$dry_run,
);

if ($version) {
	&version;

	exit 255;
}

if ($help) {
	&version;

	print '


-d <du>        Target disk usage.

-p <path>      The path to operate on.

-i <regex>     Optional ignore regex.

-i <min files> Optional minimum number of files to keep regardless of disk usage.

--pretty       Pretty print the results.

--dry_run      Do not actually delete anything. Instead just check if what it would delete is writable by the current user.

-v             Print version.
--version      Print version.

-h             Print help.
--help         Print help,

';

	exit 255;
} ## end if ($help)

my $results
	= App::FileCleanerByDiskUage->clean( path => $path, du => $du, min_files => $min_files, dry_run => $dry_run );

if ( !$pretty ) {
	print encode_json($results) . "\n";
} else {
	print JSON->new->utf8->canonical(1)->pretty(1)->encode($results);
}

if ( $results->{unlink_failed_count} > 0 ) {
	exit 1;
}
exit 0;
