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

package Zeromin2::Translate::Img0ch::v2::Archive;

use strict;
use Zeromin::Archive 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} } );
        my $zArchive = Zeromin::Archive->new($iBBS);
        _aggregate( $iKernel, $zArchive, $iBBS );
    }

    return { code => 0, archive => 1 };
}

sub _aggregate {
    my ( $iKernel, $zArchive, $iBBS ) = @_;
    my $base = $iBBS->path('kako');
    -d $base or return;

    local ( *DH, $! );
    opendir *DH, $base or $iKernel->throw_io_exception($base);
    my @dirs = readdir *DH;
    closedir *DH or $iKernel->throw_io_exception($base);

    require File::Copy;
    require File::Find;
    require File::Spec;
    my $hash = {};
    for my $dir ( File::Spec->no_upwards(@dirs) ) {
        $dir =~ /\A\d{3,3}\z/xms or next;
        $dir = File::Spec->catdir( $base, $dir );
        File::Find::find(
            {   bydepth  => 1,
                no_chdir => 1,
                untaint  => 1,
                wanted   => sub {
                    my $name = $File::Find::name;
                    -f $name
                        and $name =~ m{/(\d{9,10})\.html\z}xms
                        and $hash->{$1} = $name;
                },
            },
            $dir
        );
        for my $key ( keys %$hash ) {
            my $path = $zArchive->path($key);
            if ( !-d $path ) {
                require File::Path;
                File::Path::mkpath($path)
                    or $iKernel->throw_io_exception($path);
            }
            File::Copy::copy( $hash->{$key}, "${path}/${key}.html" )
                or $iKernel->throw_io_exception("${path}/${key}.html");
        }
        %$hash = ();
    }

    $zArchive->update();
    return;
}

1;
__END__
