#/*
# *  Copyright 2007 hkrn <hikarin@users.sourceforge.jp>
# *
# *  Licensed under the Apache License, Version 2.0 (the "License");
# *  you may not use this file except in compliance with the License.
# *  You may obtain a copy of the License at
# *
# *      http://www.apache.org/licenses/LICENSE-2.0
# *
# *  Unless required by applicable law or agreed to in writing, software
# *  distributed under the License is distributed on an "AS IS" BASIS,
# *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# *  See the License for the specific language governing permissions and
# *  limitations under the License.
# */
#
# $Id: Reaper.pm 1230 2007-10-01 13:40:05Z hikarin $
#

package Img0ch::Plugin::BBS::Reaper;

use strict;
use Zeromin::Log::Action qw();
use Zeromin::Pool qw();
use Zeromin::Subject qw();

sub work {
    my ( $iApp, $plugin_id ) = @_;
    my $will_work
        = Img0ch::Kernel::intval(
        shift @{ $iApp->get_plugin_config( $plugin_id, 'will', 1 ) } )
        || 16;

    #    int( rand($will_work) ) == 0 or return 1;

    my $iBBS     = $iApp->bbs();
    my $zSubject = Zeromin::Subject->new($iBBS);
    my $zLog     = Zeromin::Log::Action->new( $iBBS->get_kernel() );
    my $zPool    = Zeromin::Pool->new( $iBBS, 0 );
    my $bbs_name = $iBBS->get_name();
    my $ip       = $iApp->get_ip_int();

    my $byDate
        = Img0ch::Kernel::intval(
        shift @{ $iApp->get_plugin_config( $plugin_id, 'date', 1 ) } )
        || 0;
    my $byRes
        = Img0ch::Kernel::intval(
        shift @{ $iApp->get_plugin_config( $plugin_id, 'res', 1 ) } )
        || 0;
    my $byPos
        = Img0ch::Kernel::intval(
        shift @{ $iApp->get_plugin_config( $plugin_id, 'pos', 1 ) } )
        || 0;
    my $bySpeed
        = shift @{ $iApp->get_plugin_config( $plugin_id, 'speed', 1 ) } || 0;
    my $byWriteable
        = shift @{ $iApp->get_plugin_config( $plugin_id, 'writeable', 1 ) }
        || 0;
    my $cond = {
        bydate      => ( $byDate * 86400 ),
        byres       => $byRes,
        bypos       => $byPos,
        bywriteable => $byWriteable,
        byspeed     => $bySpeed,
    };

    $zSubject->load();
    for my $target ( @{ $zSubject->gets_by_condition($cond) } ) {
        my ( $key, $reason ) = @$target;
        $zPool->set_key($key);
        $zPool->create();
        $zLog->add(
            __PACKAGE__,
            0,
            $ip,
            1,
            'CREATED POOL BY REAPER PLUGIN: %s/%s BECAUSE OF %s, %s',
            [ $bbs_name, $key, $reason->{reason}, $reason->{value} ],
        );
    }

    $iApp->subject()->load();
    $zLog->save();

    return 1;
}

1;
__END__
