#/*
# *  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: Thread.pm 1102 2007-09-10 14:31:36Z hikarin $
#

package Zeromin2::Translate::Img0ch::v2::Log::Thread;

use strict;
use Img0ch::Log qw();
use Img0ch::Thread qw();
use Time::Local qw();
use Zeromin::BBS qw();

sub work {
    my ( $zClass, $iKernel ) = @_;

    my $zBBS = Zeromin::BBS->new( $iKernel, { id => 0 } );
    my $bbs_all = $zBBS->all();

    foreach my $bbs (@$bbs_all) {
        my $iBBS = Img0ch::BBS->new( $iKernel, { id => $bbs->{id} } );
        _parse( $iBBS, $iKernel ) or return { code => 1 };
    }

    return { code => 0 };
}

sub _parse {
    my ( $iBBS, $iKernel ) = @_;

    my $iConfig = $iKernel->get_config();
    my ( $id, $dir ) = ( $iBBS->get_id(), $iBBS->get_name() );
    my $path = join '/', $iConfig->get('BBSPath'), $dir, 'log/IP.cgi';
    -r $path or return { code => 0 };

    my $log = {};
    local ( $!, *FH );
    open *FH, "<${path}" or    ## no critic
        $iKernel->throw_io_exception($path);

    while ( my $line = <FH> ) {
        chomp $line;
        my ( undef, $key, undef, $host ) = split '<>', $line;
        my $ip = '';
        if ( $host =~ /\A(\d+)\.(\d+)\.(\d+)\.(\d+)\z/xms ) {
            $ip = "$1.$2.$3.$4";
        }
        else {
            $ip = join '.', unpack( 'C*', gethostbyname $host );
        }
        $host =~ /\s([\w\-]+)\z/xms;
        my $serial = $1 || '';
        my $iLog = $log->{$key};
        if ($iLog) {
            $iLog = Img0ch::Log->new( $iBBS, $key );
            $iLog->load();
            $log->{$key} = $iLog;
        }
        $iLog->set( 1, [ $key, $ip, $serial, '' ] );
    }
    close *FH or $iKernel->throw_io_exception($path);
    map { $_->save() } values %$log;

    return 1;
}

1;
__END__
