package Distribution::Cleanup::Command::JobLogs;

use strict;

use lib '/app/tools/job/lib';
use Job::Config;

use lib '/app/tools/distribution/lib';
use Distribution::Util;

use lib '/app/tools/common/lib';
use Common::Assert;

use Data::Dumper;
use File::Stat;
use Class::Date qw( localdate );
use File::Copy qw( copy move );

use base 'Distribution::Cleanup::Command';

sub synopsis {
    'Archive individual job logs into monthly directories.';
}

sub description {
    return <<EOF;
Archive all individual delivery and packager job logs into monthly archive
folders.  Logs will only be archived if they are more then 30 days old and the
archive folder is in the same directory as the log files.
EOF
}

sub execute {
    my $self   = shift;
    my $config = Job::Config->new();

    my $logFilePath = $config->get('windows_log_dir') || die;

    print "  + Start cleanup in $logFilePath\n";

    $self->_cleanup($logFilePath);
}

sub _cleanup {
    my $self = shift;
    my $path = shift;

    my $cmd = "find $path -maxdepth 1 -type f -ctime +7";

    print "  + CMD: $cmd\n";

    open( FIND, "$cmd |" ) || die $@;

    while (<FIND>) {
        chomp;
        $self->_archiveFile( $path, $_ );
    }
}

sub _archiveFile {
    my $self = shift;
    my $path = shift;
    my $file = shift || die;

    my $stat = new File::Stat($file) || die;
    my $date = localdate( $stat->ctime );
    my $dir  = sprintf( "%s/archive/%04d-%02d", $path, $date->year(), $date->month() );

    print "   - mv $file\n";
    mkdir_local($dir);
    move( $file, $dir );
}

1;
